【问题标题】:C++ read text file until specific delimiterC ++读取文本文件直到特定分隔符
【发布时间】: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;...,这是故意的。第一个字符总是'$',因为它表示章节的开始。我故意跳过它。

标签: c++ delimiter readfile


【解决方案1】:

您正在使用 C 文件 API,您应该使用 C++ iostream API。

要阅读章节,您应该使用std::getline'$' 作为分隔符参数。这意味着您无需担心缓冲区分配,因为字符串对象会自动分配它。

循环也变得非常简单。

while(std::getline(strm, str, '$').good())
    do_something_with_chapter(str);

【讨论】:

    【解决方案2】:

    一个错误是,如果你的while循环,循环,那么语句

    chapterBuffer.append(charBuffer);
    

    将尝试将未终止的字符缓冲区附加到 chapterBuffer 中 - 这不是一件好事。无论您是否找到“$”,您都必须在 for 循环中维护;如果你没有,那么你将不得不终止 charBuffer;或者您可以为 charBuffer 分配 buffersize + 1 个字节,并在循环之前设置 charBuffer[buffersize] = '\0';

    【讨论】:

    • 这似乎是一个非常合乎逻辑的答案,我回家后会测试一下!我一直在寻找类似的东西,但我自己没有找到!
    猜你喜欢
    • 2015-03-08
    • 2011-10-03
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多