【fstream::open】
函数原型
void open (const char* filename,
ios_base::openmode mode = ios_base::in | ios_base::out);
其中 filename 为文件名字
openmode 如下:
in input 以读的方式打开,即input 内存
out output 以写的方式打开 , 即output 内存,写入磁盘
binary binary 二进制模式
ate at end 输出位置在文件结尾
app append 追加写,需要已经存在的文件
trunc truncate 文件打开之前的任何内容都会丢失
###
fstream 中函数模型
/**
* @brief Opens an external file.
* @param s The name of the file.
* @param mode The open mode flags.
* @return @c this on success, NULL on failure
*
* If a file is already open, this function immediately fails.
* Otherwise it tries to open the file named @a s using the flags
* given in @a mode.
**/
__filebuf_type*
open(const char* __s, ios_base::openmode __mode);
/**
* @brief Opens an external file.
* @param s The name of the file.
* @param mode The open mode flags.
* @return @c this on success, NULL on failure
*/
__filebuf_type*
open(const std::string& __s, ios_base::openmode __mode)
{ return open(__s.c_str(), __mode); }
代码实现
#include<fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("myfile.txt",ios::app|ios::in|ios::out);
fs<<"more strings "<<endl;
fs.close();
return 0;
}
多次执行 ,文件内容累加。
另外 fstream中 与fopen() 参数的比较:如下
/**
*
* +---------------------------------------------------------+
* | ios_base Flag combination stdio equivalent |
* |binary in out trunc app |
* +---------------------------------------------------------+
* | + "w" |
* | + + "a" |
* | + "a" |
* | + + "w" |
* | + "r" |
* | + + "r+" |
* | + + + "w+" |
* | + + + "a+" |
* | + + "a+" |
* +---------------------------------------------------------+
* | + + "wb" |
* | + + + "ab" |
* | + + "ab" |
* | + + + "wb" |
* | + + "rb" |
* | + + + "r+b" |
* | + + + + "w+b" |
* | + + + + "a+b" |
* | + + + "a+b" |
* +---------------------------------------------------------+