【发布时间】:2013-03-19 12:40:21
【问题描述】:
好的,所以我有一个大文件,我想一次读一章。
章节由'$' 分隔。
我对 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;
}
结果应该没问题。我还没有到达文件末尾。所以它可能会在那里失败。 然而,它似乎是随机的(一致的,但在看似随机的位置)。 失败将导致在字符串中注入垃圾数据(例如 8 个字符),然后再次注入正常数据。
有没有人知道是什么原因造成的,或者有没有人有更合适的 C++ 方法来做到这一点?带有字符串阅读器的东西?
提前致谢,
-笑脸器
【问题讨论】:
-
查看
std::getline。当然你应该了解更多关于 C++ input/output facilities. -
使用
getline(file, data, '$'),将二十行代码替换为一行。 -
缓冲区中的第一个字符未被扫描。使用
for (int i =0; ... -
getline 是我将在所有工作后测试替换的东西,用于学习目的:) 至于
(int i=1;...,这是故意的。第一个字符总是'$',因为它表示章节的开始。我故意跳过它。