从文件TEST中读出字符并写入TEST1里,要求均附加错误检查--p209_5

源程序:

#include <iostream>

#include <fstream>  //包含文件操作的头文件

using namespace std;

void main()

{

  ifstream txt1("c:\TEST.txt");

  //建立输入文件对象指针txt1,指向文件"TEST.txt",

  //文件"TEST.txt"要预先放在根目录下。

  ofstream txt2("c:\TEST1.txt"); //建立输出文件对象txt2

  char c;

  if (!txt1)

  {

    cout << "文件打不开!" << endl;

    return;

  }

  if (!txt2)

  {

    cout << "没有正确建立文件!" << endl;

    return;

  }

  while (1)

  {

    txt1 >> noskipws; //这语句要写上,否则文件中的空格会被符忽略掉

    txt1 >> c;  //从文件中提取字符

    if (txt1.eof())

    {

      txt1.close();

      return;

    }

    cout << c;//打印字符

    txt2 << c;//将字符写到文件TEST1.txt中

  }

  system("pause");

}

运行结果:

 

原文地址:https://www.cnblogs.com/duanqibo/p/11900570.html