1. 概述
写文件是 MFC 应用程序最基本的功能,本文记录了如何使用 fstream 来写文件,并用 ios 指定打开文件的方式。
2. 头文件
#include "fstream.h"
3.可重用代码
fstream _Out("data.txt",ios::out);
_Out << "Data1 = " << Data1 << endl;
...
_Out.close();
4. 说明
关于ios
ios 指定打开文件的方式,有如下几种。如果需要指定多种方式,使用位运算符“|”来组合它们,例如 ios::out|ios::app。
- ios::app 打开文件,并在文件结尾追加数据.
- ios::ate Opens an existing file (either input or output) and seeks the end.
- ios::in Opens an input file. Use ios::in as an open_mode for an ofstream file to prevent truncating an existing file.
- ios::out Opens an output file. When you use ios::out for an ofstream object without ios::app, ios::ate, or ios::in, ios::trunc is implied.
- ios::nocreate 只能打开一个已有的文件,否则会出错.
- ios::noreplace 只能打开一个不存在的文件,否则会出错(?).
- ios::trunc 打开一个文件并替换掉它,如果它已有的话(?).
- ios::binary 以二进制模式打开文件(默认为文本模式).