linux+c+逐行读文件内容,使用C ++中的ifstream逐行读取文件

在C ++中逐行读取文件可以通过某些不同的方式完成。

[快]循环使用std :: getline()

最简单的方法是使用std :: getline()调用打开std :: ifstream和循环。 代码简洁易懂。

#include

std::ifstream file(FILENAME);

if (file.is_open()) {

std::string line;

while (getline(file, line)) {

// using printf() in all tests for consistency

printf("%s", line.c_str());

}

file.close();

}

[Fast]使用Boost的file_description_source

另一种可能性是使用Boost库,但代码更加冗长。 性能与上面的代码非常相似(Loop with std :: getline())。

#include

#include

#include

namespace io = boost::iostreams;

void readLineByLineBoost() {

int fdr = open(FILENAME, O_RDONLY);

if (fdr >= 0) {

io::file_descriptor_source fdDevice(fdr, io::file_descriptor_flags::close_handle);

io::stream <:file_descriptor_source> in(fdDevice);

if (fdDevice.is_open()) {

std::string line;

while (std::getline(in, line)) {

// using printf() in all tests for consistency

printf("%s", line.c_str());

}

fdDevice.close();

}

}

}

[最快]使用C代码

如果性能对您的软件至关重要,您可以考虑使用C语言。 此代码可以比上面的C ++版本快4-5倍,请参阅下面的基准测试

FILE* fp = fopen(FILENAME, "r");

if (fp == NULL)

exit(EXIT_FAILURE);

char* line = NULL;

size_t len = 0;

while ((getline(&line, &len, fp)) != -1) {

// using printf() in all tests for consistency

printf("%s", line);

}

fclose(fp);

if (line)

free(line);

基准 - 哪一个更快?

我已经使用上面的代码完成了一些性能基准测试,结果很有趣。 我已经使用包含100,000行,1,000,000行和10,000,000行文本的ASCII文件测试了代码。 每行文本平均包含10个单词。 该程序使用-O3优化编译,其输出转发到/dev/null,以便从测量中删除记录时间变量。 最后,但并非最不重要的是,为了保持一致,每段代码都使用printf()函数记录每一行。

结果显示每段代码读取文件所用的时间(以毫秒为单位)。

两种C ++方法之间的性能差异很小,在实践中不应有任何区别。 C代码的性能使得基准测试令人印象深刻,并且在速度方面可以改变游戏规则。

10K lines 100K lines 1000K lines

Loop with std::getline() 105ms 894ms 9773ms

Boost code 106ms 968ms 9561ms

C code 23ms 243ms 2397ms

fKKqc.png