写入文件:
- 包含头文件fstream
- 创建一个ofstream对象
- 打开文件
- 像使用cout一样使用ofstream对象
代码如下:
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 ofstream outfile; //create object for output 8 outfile.open("objectfile"); //associate with a file 9 outfile<<数据 //output the data 10 outfile.close(); //done with file 11 return 0; 12 }
另外一种文件写入方法:
ofstream outfile("objectfilename", ios::out); //ios::app 是追加数据写入文件里
outfile<<数据
outfile.close();
读取文件:
读取文件的方法与写入文件的方法差不多,不同的是读取文件就像cin那样输入数据一样用运算符>>来读取文件的数据,而且读取文件之前会有一个判断文件是否存在
代码如下:
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 ifstream inFile; 8 inFile.open("objectfilename"); //input the objectfile 9 if(!inFile.is_open()) 10 { 11 cout<<"the file is not exist"<<endl; 12 } 13 inFile>>数据; 14 inFile.close(); //done with file 15 return 0; 16 }
另外一种读取文件的方法:(这种方法看起来更简单点)
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 ifstream inFile("objectfilename", ios::in); //input the objectfile 8 if(!inFile)) 9 { 10 cout<<"the file is not exist"<<endl; 11 } 12 inFile>>数据; 13 inFile.close(); //done with file 14 return 0; 15 }
eof()---->该函数是拿来判定是否读取到文件尾
PS:弱菜自学,为了方便查看而已,勿喷~TX~
浙公网安备 33010602011771号