从文件中逐块读取,然后逐行拆分测试
Reading block by block from file then split test line by line
>我正在从文件读取到缓冲区中,然后将读取的文本划分为字符串,其中每个文本以新行结尾形成一个新字符串。
这是我的代码:
int ysize = 20000;
char buffer2[ysize];
int flag = 0;
string temp_str;
vector<string> temp;
while(fread(buffer2, ysize, 1, fp2)>0){
//printf("%s", buffer2);
std::string str(buffer2);
//push the data into the vect
std::string::size_type pos = 0;
std::string::size_type prev = 0;
/*means the last read did not read a full sentence*/
if (flag == 1) {
if (buffer[0] == 'n') {
//this means we have read the last senstense correctly, directly go to the next
}
else{
if((pos = str.find("n", prev)) != std::string::npos){
temp_str+=str.substr(prev, pos - prev);
temp.push_back(temp_str);
prev = pos + 1;
}
while ((pos = str.find("n", prev)) != std::string::npos)
{
temp.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
temp.push_back(str.substr(prev));
if (buffer2[19999] != 'n') {
//we did not finish readind that query
flag = 1;
temp_str = temp.back();
temp.pop_back();
}
else{
flag = 0;
}
}
}
else{
while ((pos = str.find("n", prev)) != std::string::npos)
{
temp.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
temp.push_back(str.substr(prev));
if (buffer2[19999] != 'n') {
//we did not finish readind that query
flag = 1;
temp_str = temp.back();
temp.pop_back();
}
else{
flag = 0;
}}
}
问题是这不能正确读取数据,它几乎消除了一半的文本。
我不确定我在这里错过了什么。我的想法是逐块读取数据,然后逐行除以,这就是 while 循环中的内容。我正在使用标志处理溢出情况。
首先要注意的是,fread 不会神奇地创建一个以 null 结尾的字符串,这意味着 std::string str(buffer2( 将导致未定义的行为。所以你应该做一些类似的事情
int nread = 0;
while( (nread =fread(buffer2, ysize-1, 1, fp2)) > 0 ){
buffer2[nread] = 0;
std::string str(buffer2);
...
为了避免您在此处实现的缓冲方法,您可以使用 fgets 逐行读取,然后您只需要担心连接比读取缓冲区长的行。
除了我发现了一个问题:如果缓冲区中的第一个字符是换行符并且 flag==1,则跳过整个当前缓冲区并在仍有可用数据时读取下一个缓冲区。(我假设缓冲区[0]实际上是指缓冲区2[0](。
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- 打印逐行存储的文本文件
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- C++如何将字符串逐行转换为双精度
- 在 c++ 中逐行阅读字符串,不要以空格停止
- 使用 QT 逐行读取 JSON
- 逐行读取文件,并将数据插入变量和数组中
- 逐行从文本文件中读取 |C++
- 我遇到使用 c++ 逐行读取输入文件的问题
- 无法逐行读取.csv文件
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- C ++ txt 文件成数组逐行字符串和 int 用于纸牌游戏
- 如何将文件逐行读取到矢量中,然后打印矢量
- C++逐行读取文件
- 如何逐行读取文件并分隔行组件?
- C++ 逐行从文件(包含空格)读取数据
- 对包含整数的文本文件进行排序时,必须逐行进行排序
- 从文件中逐块读取,然后逐行拆分测试
- 逐行读取文件,然后写入C 中的数组