C++文件流 fstream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013043408/article/details/83621182

提供了三个类

类名 描述 头文件
ofstream 输出文件流,将内存数据输出到文件,写文件。 ofstream
ifstream 输入文件流,将文件内容输入到内存,读文件。 ifstream
fstream 文件流,同时具有ofstream和istream两种功能。 fstream

API

api 描述
open() 打开文件。仅在写文件模式下,目标文件不存在才会创建文件。
close() 关闭文件
<< 向文件写入数据。
>> 从文件读取数据,箭头朝哪个方向,数据就流向哪里。

open()的第二个参数

模式 描述
ios::app 追加模式。写指针定位到文件末尾,但读指针仍在文件起始位置。
ios::ate 将读写指针都定位到文件末尾。
ios::trunc 打开文件后,清空文件内容。
ios::in 文件可读。
ios::out 文件可写。

三个类,open的第二个参数,的默认值

类名 open第二个参数默认值
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out

写读文件

写文件

ofstream fout;	
fout.open("file.txt");	
if (!fout.is_open()){		
    cout << "open file failed." << endl;	
} 	

for (int i = 1; i <= 10; ++i){		
    fout << i << "_";	
} 	

fout.close();

读文件

ifstream fin;	
fin.open("file.txt");	
if (!fin.is_open()){		
    cout << "open file failed." << endl;	
} 

for (int i = 0; i < 10; ++i){		
    int temp = 0;		
    char space = 0;		
    fin >> temp >> space;		
    cout << temp << space;	
} 

fin.close();

输出结果
文件:1_2_3_4_5_6_7_8_9_10_
控制台:1_2_3_4_5_6_7_8_9_10_

文件位置指针

方法 描述
seekp(5, ios::beg) 从文件初始位置,正数第5个
seekp(5, ios::cur) 从当前位置,正数第5个
seekp(5, ios::end) 从文件末尾位置,倒数第 5个

猜你喜欢

转载自blog.csdn.net/u013043408/article/details/83621182