如何在 C++ 中逐行读取文件

本文将介绍如何在 C++ 中逐行读取文件。

使用 std::getline() 函数逐行读取文件

getline() 函数是 C++ 中逐行读取文件的首选方式。该函数从输入流中读取字符,直到遇到定界符 char,然后将它们存储在一个字符串中。定界符作为第三个可选参数传递,默认情况下,它被认为是一个新的行字符/n

由于 getline 方法在数据可以从流中读取的情况下会返回非零值,所以我们可以把它作为一个 while 循环条件,继续从文件中检索行,直到到达文件的终点。需要注意的是,最好用 is_open 方法验证输入流是否有关联的文件。

#include <iostream>#include <fstream>#include <vector>using std::cout; using std::cerr;
using std::endl; using std::string;
using std::ifstream; using std::vector;
int main()
{
    string filename("input.txt");
    vector<string> lines;
    string line;
    ifstream input_file(filename);
    if (!input_file.is_open()) {
        cerr << "Could not open the file - '"
             << filename << "'" << endl;
        return EXIT_FAILURE;
    }
    while (getline(input_file, line)){
        lines.push_back(line);
    }
    for (const auto &i : lines)
        cout << i << endl;
    input_file.close();
    return EXIT_SUCCESS;
}

使用 C 库的 getline() 函数逐行读取一个文件

getline 函数的使用方法类似于逐行循环浏览文件,并将提取的行存储在字符串变量中。主要的区别是,我们应该使用 fopen 函数打开一个文件流,该函数返回 FILE*对象,随后作为第三个参数传递。

注意,getline 函数存储在 char 指针,它被设置为 nullptr。这是有效的,因为函数本身是为检索字符动态分配内存的。因此,即使 getline 调用失败,char 指针也应该被程序员明确释放。

另外,在调用函数之前,将类型为 size_t 的第二个参数设置为 0 也很重要。你可以在这里看到 getline 函数的详细手册。

#include <iostream>#include <vector>using std::cout; using std::cerr;
using std::endl; using std::string;
using std::vector;
int main()
{
    string filename("input.txt");
    vector<string> lines;
    char* c_line = nullptr;
    size_t len = 0;
    FILE* input_file = fopen(filename.c_str(), "r");
    if (input_file == nullptr)
        return EXIT_FAILURE;
    while ((getline(&c_line, &len, input_file)) != -1) {
        lines.push_back(line.assign(c_line));
    }
    for (const auto &i : lines) {
        cout << i;
    }
    cout << endl;
    fclose(input_file);
    free(c_line);
    return EXIT_SUCCESS;
}