从文件中逐块读取,然后逐行拆分测试

Reading block by block from file then split test line by line

本文关键字:然后 逐行 拆分 测试 读取 文件      更新时间:2023-10-16

>我正在从文件读取到缓冲区中,然后将读取的文本划分为字符串,其中每个文本以新行结尾形成一个新字符串。

这是我的代码:

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](。