学习文件流 (1)
1 #include <iostream> 2 #include<fstream> 3 #include<string> 4 5 using namespace std; 6 7 int main() 8 9 { 10 ofstream outfile("test.txt");//创建新的文件 11 outfile << "hello file!";//这些文字进入到流中,这个流被写道文件里 12 outfile.close();//把这个文件关闭了 13 14 15 string file("one.txt"); 16 //ifstream infile(file.c_str());//一定要用C风格的字符串 17 ifstream infile;//先创建一个Infile就没有绑定文件 18 infile.open(file.c_str());//再通过open来绑定 19 20 // if(infile)//检查打开文件是否成功 21 if(!infile) 22 { 23 cerr << "error: unable to open input file:" 24 << file << endl; 25 return -1; 26 } 27 string s; 28 29 while(infile >> s) 30 cout << s << endl; 31 infile.close();//记得把文件关闭 one.txt 32 infile.clear();//不仅要close,还要用clear恢复流的状态 33 34 file ="two.txt"; 35 infile.open(file.c_str()); 36 infile.open("two.txt"); 37 if(!infile) 38 { 39 40 cerr << "error: unable to open input file:" 41 << file << endl; 42 return -1; 43 } 44 while(infile >> s) 45 46 { 47 48 cout << s << endl; 49 } 50 51 //cout << "读到的内容:" << s << endl; 52 53 54 55 return 0; 56 }