C/C++分别读取文件的一行

C语言读取文件的一行:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 200

int main(int argc, char* argv[])
{
    FILE* fp;
    char buffer[MAX_LINE];

    fp = fopen("test.txt", "r");
    if (fp == NULL)
    {
        perror("File open");
        exit(1);
    }

    while (fgets(buffer, MAX_LINE, fp) != NULL)
    {
        fputs(buffer, stdout);
    }

    return 0;
}

程序输出:

C++语言读取文件的一行:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char** argv)
{
    ifstream ifs("test.txt");

    string str;
    while (getline(ifs, str))
    {
        cout << str << endl;
    }

    return 0;
}

程序输出:

总结:C语言使用fgets()读取文件的一行内容,C++使用getline()读取文件的一行内容。

C++的getline比较形象的说明了可以读取一样内容。

原文地址:https://www.cnblogs.com/Robotke1/p/3079648.html