一、写入文件
要让程序写入文件,可以这样做:
1.创建一个ofstream对象来管理输出流;
2.将该对象与特定的文件关联起来;
3.以使用cout的方式使用该对象,唯一的区别是输出将进入文件,而不是屏幕
先包含头文件fstream
#include <fstream>
然后声明一个ofstream对象
ofstream fout; // create an ofstream object named fout
使用open方法将fout对象和特定的文件关联起来
在fstream类中,成员函数open()实现打开文件的操作,从而将数据流和文件进行关联,通过ofstream,ifstream,fstream对象进行对文件的读写操作。
函数:open() void open ( const char * filename,ios_base::openmode mode = ios_base::in | ios_base::out );
void open(const wchar_t *_Filename, ios_base::openmode mode= ios_base::in | ios_base::out,int prot = ios_base::_Openprot);
参数: filename 待操作的文件名
mode 打开文件的方式
prot 打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:
- ios::app: 以追加的方式打开文件
- ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
- ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
- ios::in: 文件以输入方式打开(文件数据输入到内存)
- ios::out: 文件以输出方式打开(内存数据输出到文件)
- ios::nocreate:不建立文件,所以文件不存在时打开失败
- ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
- ios::trunc: 如果文件存在,把文件长度设为0
可以用“或”把以上属性连接起来,如ios::out|ios::binary
fout.open("test.txt"); 或者 ofstream fout("test.txt");// 写文件
// 定义一个输出文件流对象, 关联一个文件
// 关联成功,相当于打开了一个文件,之后文件流对象的操作相当于对文件的操作
ofstream fout("test.txt");
if (!fout) // ofstream 重载了!运算符,如果打开失败,返回真
cout << "文件打开失败" << endl;
就可以向文件输入数据:
fout("hello world!"); 或者fout << "hello world" << endl;
关闭文件连接:
fout.close();
二、读入文件
ifstream fin("test.txt");
if (!fin)
cout << "文件打开失败" << endl;
char str[100];
for (int i = 0; i < 4; i++) //读四行
{
fin.getline(str, sizeof(str)); //读一行数据,放入str中
cout << str << endl;
}
fin.ignore(4); //忽视跳过4个字符
char c;
fin >> c;
cout << c << endl; //结果就读了一个字符‘o'
char ch;
while ((ch=fin.get()) != EOF)
cout << ch; //输出缓冲区里的
fin.close();