C和C++的文件操作

首先来说C;

  开启重定向语句:

    freopen("input.txt", "r", stdin); //将之后的读入都从input.txt中读入

    freopen("output.txt", "w", stdout); //将之后的写入都写到output.txt中

  关闭重定向语句:

    关闭读入:freopen("CON", "r", stdin);

    关闭写入写文件后:freopen("CON", "w", stdout);

  fopen版输入输出:

    FILE *fin, *fout;

    fin=fopen("input.txt", "rb");

    fout=fopen("output.txt", "wb");

    然后后面scanf("%d", &n)之类的全改成fscanf(fin, "%d", &n)

        printf("%d", n)之类的全改成fprintf(fout, "%d", n)

  fopen版关闭输入输出:

    fclose(fin);

    fclose(fout);

然后我们说C++;

  文件流输入输出:

    ifstream fin("input.txt");

    ofstream fout("output.txt");//可以使用fin.is_open()和fout.is_open()来确认文件是否被载入流中

    然后后面的cin>>x之类的全改成fin>>x

         cout<<x之类的全改成fout<<x

         cin.get(char)之类的全改成fin.get(char)

         cin.getline(char*, int)之类的全改成fin.getline(char*, int)

         getline(cin, string)之类的全改成getline(fin, string)

  文件流的关闭:

    fin.close();

    fout.close();

    //注意:如果使用fin多次读入文件或读入不同的文件,记得使用fin.clear()清除缓冲区。

总结:

  重定向最方便,但很多文件读写的比赛不承认

  文件流功能最全,但速度感人

  fopen速度快,但是写起来比较麻烦

  

原文地址:https://www.cnblogs.com/St-Lovaer/p/11393424.html