The last time the file was opened in the program, it failed and the final code problem was:
Fopen_s (&pfile,strpath.c_str (), "rb+");
The main is "rb+".
First of all, let's look at the introduction, mainly the CRT-related file open operation under Windows.
The C89 standard is fopen:
FILE * fopen (const char *file, const char *mode);
There are Fopen_s,_fsopen extensions in Windows:
errno_t fopen_s (
file** PFile,
const Char *filename,
const CHAR *mode
);
FILE *_fsopen (
const Char *filename,
const Char *mode,
int Shflag
);
By looking at vs2008/2010 under the CRT source code we can see that fopen, fopen_s are implemented by calling _fsopen:
FILE * fopen (const char *file, const char *mode) {return (_fsopen (file, mode, _sh_denyno));} errno_t fopen_s (FILE * * pfile, const char *file, const char *mode) {_validate_return_errcode ((pfile! = NULL), EINVAL); *pfile = _fsopen (file, mode, _sh_secure); if (*pfile! = NULL) return 0; return errno;}
The main reason is the 3rd parameter of _fsopen: int shflag:
#define _SH_DENYRW 0x10/* Deny Read/write mode */#define _SH_DENYWR 0x20/Deny write mode */#define _sh _denyrd 0x30/* Deny read mode */#define _SH_DENYNO 0x40 */deny None mode */#define _SH_SECURE 0x80 /* Secure Mode */
And through the source can be seen, so-called _sh_secure is/* Share Read access only if read-only * *
So the difference is that fopen is _sh_denyno is shared read and write, and fopen_s is _sh_secure that is in read-only mode to share the read, others do not share.
So back to the beginning of the problem, the reason to read the file failed because several processes are reading this file at the same time, and the mode is "rb+" is opened for reading and writing, so fopen_s will be locked by a process, not shared to other processes. The solution is to change "rb+" to "RB" or read-only mode.
Summary: When you open a file, you can minimize the read and write flags as much as possible, especially many times only need to read only, do not add to write.
This article is from the "V" blog, be sure to keep this source http://4651077.blog.51cto.com/4641077/1622303
File Operation Fopen,fopen_s,_fsopen