C++文件I/O选项卡分隔的数据

C++ File I/O Tab separated data

本文关键字:分隔 数据 选项 文件 C++      更新时间:2023-10-16

我有一个数字如下的文本文件:num1制表符num2制表符……num22换行符。。.

我想阅读num1检查,看看它是否等于3,如果是,将整行复制到一个新文件中。做这件事最快的方法是什么?这个文件相当大,80Mb+。此外,num 1是重复的,即它以0.001的步长从0变为3。所以我只需要每隔这么多步就读一次。我不知道如何告诉计算机先验地跳过x行?

谢谢。

如果您已经说过运行时性能不是主要问题,那么以下内容是清晰简洁的:

#include <string>
#include <fstream>
void foo(std::string const& in_fn, std::string const& out_fn)
{
    std::ifstream is(in_fn);
    std::ofstream os(out_fn);
    std::string line;
    while (std::getline(is, line))
        if (line.size() && std::stoi(line) == 3)
            os << line << 'n';
}

(假定支持C++11;为简洁起见,省略了错误处理。)

伪代码可以如下所示:

while (not eof) {
    fgets(...);
    find TAB symbol or end of line
    get string between two marks 
    cleain it from spaces and other unnecessary symbols
    float fval = atof(...);
    if (fval == 3) {
        write the string into new file
    }
}