fstream读写文件时,Invalid sharing flag

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.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值