views:

155

answers:

1

I am working on some legacy code which opens a file and adds binary data to the file:

    std::ifstream mInFile;

    #ifdef WINDOWS
        miWindowsFileHandle = _sopen(filename.c_str(), O_RDONLY , SH_DENYWR, S_IREAD);
    #endif

    mInFile.open(filename.c_str(), std::ios_base::binary);

For some reason the code opens the file twice. Is this because _sopen is used to lock the file in windows?

If so, how come std::ifstream::open doesn't lock the file?

Is there a way to check if a windows file handle has already been closed?

+2  A: 

It opens twice because the first one opens it, and locks it. Then fstream opens it again (somewhat contradictory to the intent of the previous statement.)

On how to just lock the file, check this question out.

GMan
So I could just go mInFile.open() and then use LockFileEx. This would save me trying to close two file handles.
Seth
Maybe. I think `LockFileEx` needs a handle to a file, and you get that handle with OS specific functions. Like the other question said, you'd have to somewhat rewrite fstream around that.
GMan
No need to use `LockFileEx`, because it uses file handle that can be already open with `FILE_SHARE_READ` option.
Kirill V. Lyadvinsky