首页 > 编程语言 > 详细

C++ 简单文件读写

时间:2016-09-18 23:29:27      阅读:282      评论:0      收藏:0      [点我收藏+]

需要包括库文件

#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();  

}  

 

C++ 简单文件读写

原文:http://www.cnblogs.com/yang-xiong/p/5883390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!