C++ 简单文件读写

需要包括库文件

#include <fstream>

(1)      ofstream:写操作,输出文件类;

(2)      ifstream:读操作,输入文件类;

(3)      fstream:可同时读写的文件类。

一般使用ofstream 和ifstream更加清楚明了

 ifstream fin("input.txt");  

 ofstream fout("input.txt");  

if (! fin.is_open())    { cout << "Error opening file"; exit (1); }   //判断是否open成功

f (! out.is_open())    { cout << "Error opening file"; exit (1); }   //判断是否open成功

“>>” 从文件读入数据, “<<”数据写入文件

使用getline 读入一行数据到字符数组:

char buffer[256];  

while (fin.getline (buffer,256) ) {  //或者! fin.eof()  

cout << buffer << endl;  

 }  

、、、、、、、、、、、、、、、、、、、、

使用geline读入一行数据到字符串:

string s;

while( getline(fin,s) ){

cout << "Read from file: " << s << endl; 
}

、、、、、、、、、、、、、、、、、、、、

使用>>逐词读取,按空格区分

string s;  

while( fin >> s ) {

cout << "Read from file: " << s << endl;  
}

、、、、、、、、、、、、、、、、、、、、

使用get()读取一个字符

char c;

while(!fin.eof()){

c = fin.get()

cout<<c<<endl;

}

、、、、、、、、、、、、、、、、、、、、

使用<<写文件

if (fout.is_open()) {  

fout<< "This is a line.\n";  

fout<< "This is another line.\n";  

fout.close();  

}  

 

posted @ 2016-09-18 22:53  熊阳  阅读(540)  评论(0编辑  收藏  举报