好的,所以我有一个很大的文件,我想一次读一章。
章节由 '$'
分隔。
我还不太熟悉 C++,所以我做了一些可以在一章中阅读的东西,就像我期望在 C/C++ 中看到的那样。
#include <nds.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <sstream>
int dataFileLoc = 7;
std::string fileReader(){
FILE * dataFile;
std::string chapterBuffer = "";
const int buffersize = 1024;
char charBuffer[buffersize];
bool foundEnd = false;
dataFile = fopen("xc3_.tsc", "rt");//open data file
fseek(dataFile,dataFileLoc,SEEK_SET);
while(!foundEnd){
fread(charBuffer,1,buffersize,dataFile);
for(int i=1; i<buffersize; i++){
if(charBuffer[i] == '$'){
foundEnd = true;
charBuffer[i] = '\0';
dataFileLoc = ftell(dataFile)-(buffersize-i);
break;//break to spare some time
}
}
chapterBuffer.append(charBuffer);
}
fclose(dataFile);//done with the file for now.
checkerTemp(chapterBuffer);
return chapterBuffer;
}
结果应该没问题。我还没有到达文件末尾。所以它可能在那里失败。 然而,它看起来似乎是随机的(一致,但在看似随机的位置)。 失败将导致在字符串中注入(inject)垃圾数据(例如 8 个字符),然后再次注入(inject)正常数据。
有没有人知道是什么导致了这种情况,或者有没有人有更合适的 C++ 方法来做到这一点?带字符串阅读器的东西?
提前致谢
-笑脸生成器
最佳答案
您正在使用 C 文件 API,您应该使用 C++ iostream API。
要阅读章节,您应该使用 std::getline
并将 '$'
作为分隔符参数。这意味着您无需担心缓冲区分配问题,因为字符串对象会自动分配它。
循环也变得非常简单。
while(std::getline(strm, str, '$').good())
do_something_with_chapter(str);
关于C++读取文本文件直到特定的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499790/