ofstream类的默认构造函数如下:
ofstream::ofstream(const char* filename, int mode = ios::out, int openport = filebuf::openport);
filename是要打开的文件名,
mode是打开的方式,
openport是打开文件的属性。
mode可以设置的方式如下:
ios::app 以追加的方式打开
ios::ate 文件打开后定位到文件尾
ios::binary 以二进制方式打开文件,默认是以文本方式打开
ios::in 文件以读(输入)方式打开
ios::out 文件以写(输出)方式打开
ios::trunc 如果文件存在,则把文件清空。
以上属性用“|”(按位或)连接起来。
openprot属性如下:
0 普通文件
1 只读文件
2 隐含文件
4 系统文件
以上属性可以用加或者按位或方式组织起来,比如1|2和3都代表既是只读又是隐含文件。
在windows操作系统中可以不要第三个参数,如果加入第三个参数,那第三个参数是打开文件的共享方式,也就是打开这个文件时,其他进程是否可以读写该文件。
共享方式参数可以是下面的值:
0x10 //_SH_DENYRW Denies read and write access to the file
0x20 //_SH_DENYWR Denies write access to the file
0x30 //_SH_DENYRD Denies read access to the file.
0x40 //_SH_DENYNO Permits read and write access
其他值都会报 "Invalid sharing flag "的错误。
ofstream hFile("c:\\1.txt", ios::out, _SH_DENYRW); // _SH_DENYRW is deny read and write
if (!hFile) // if the file could open, hFile is a handle, else is zero
{
cout << "write fail!" << endl; cout << "access is denies,maybe the file is readonlys,or use deny read opened of other process." << endl;
}
else{
hFile << "by coderlee writes";
cout << "write success!" << endl;
}
hFile.close(); // opened file need close.