ifstream由istream派生而来,从文件中读取;ofstream由ostream派生而来,写到文件中去;fstream由iostream派生而来,读写文件;

IO
 1 #include "stdafx.h"
 2 #include <fstream>
 3 #include <iostream>
 4 #include <string>
 5 using namespace std;
 6 int _tmain(int argc, _TCHAR* argv[])
 7 {
 8     ifstream infile;
 9     ofstream outfile;
10     string filename = "D:/Program Files/C++_CODE/streamtest/Debug/201204.txt";//注意路径
11     string print;
12     infile.open(filename.c_str());//打开文件
13     if(!infile) //检查是否打开
14     {
15      cout<<"open file is error!"<<endl;
16      return -1;
17     }
18     else
19     {
20         while(!infile.eof())
21      {
22         getline(infile,print);//读内容
23         cout<<"Today I want to say : "<<print.c_str()<<endl;
24      }
25      infile.close(); //关闭文件
26      infile.clear(); //清除流状态
27     }
28     string rfilename="D:/Program Files/C++_CODE/streamtest/Debug/201204_R.txt";
29     outfile.open(rfilename.c_str());
30     if(!outfile)
31     {
32      cout<<"open file is error!"<<endl;
33      return -1;
34     }
35     else
36     {
37      outfile<<"I hate you!";//往打开的文件中写内容
38      outfile.close();
39     }
40     return 0;
41 }

相关文章:

  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-12-15
  • 2021-11-27
  • 2021-09-09
  • 2021-12-11
猜你喜欢
  • 2022-02-08
  • 2021-11-06
  • 2021-05-30
  • 2021-11-09
  • 2021-04-24
相关资源
相似解决方案