头文件:fstream
1、简单使用
//i、o表示输入、输出。f表示文件。stream表示流。
ifstream fin(filename,openmode=iso::in);
ifstream fout(filename,openmode=iso:out);
例:ifstream in("a.in");
ofstream out("a.out");
for(string str;getline(in,str);)
out<<str<<endl;
getline(in,str)从文件流中读入一行数据,由于整行地读入,文件中的换行符都被丢掉了,为了照文件原样输出,在out上输出str的同时,还要再补上一个回车。
2、详细介绍
提供了三个类,用来实现c++对文件的操作。(文件的创建,读写)。
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream - 打开文件供读写
实际上,文件类型可以分为两种: 文本文件和二进制文件.
文本文件保存的是可读的字符, 而二进制文件保存的只是二进制数据。利用二进制模式,你可以操作图像等文件。用文本模式,你只能读写文本文件。否则会报错。
例一: 写文件
1、声明一个ofstream变量
2、调用open方法,使其与一个文件关联
3、写文件
4、调用close方法.
#include <fstream.h>
void main
{
ofstream file;
file.open("file.txt");
file<<"Hello file/n"<<75;
file.close();
}
例二: 读文件
1.声明一个ifstream变量.
2. 打开文件.
3. 从文件读数据
4. 关闭文件.
#include <fstream.h>
void main
{
ifstream file;
char output[100];
int x;
file.open("file.txt");
file>>output;
cout<<output;
file>>x;
cout<<x;
file.close();
}
open函数的参数定义了文件的打开模式。总共有如下模式
- 属性列表
ios::in 读
ios::out 写
ios::app 从文件末尾开始写
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
Notes
● 默认模式是文本
● 默认如果文件不存在,那么创建一个新的
● 多种模式可以混合,用|(按位或)
● 文件的byte索引从0开始。(就像数组一样)
我们也可以调用read函数和write函数来读写文件。
文件指针位置在c++中的用法:
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::end)
int fl_sz = file.tellg();
file.seekg(0,ios::beg);
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
例子:
char ch;
ifstream file("kool.cpp",ios::in|ios::out);
if(file.good()) cout<<"The file has been opened without problems;
else cout<<"An Error has happend on opening the file;
while(!file.eof())
{
file>>ch;
cout<<ch;
}