Using std:fstream how to deny access (read and write) to the file

前端 未结 3 719
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 11:33

How can I deny access to a file I open with fstream? I want to unable access to the file while I\'m reading/writing to it with fstream?

相关标签:
3条回答
  • 2020-11-30 11:55

    There is no way to do this in native C++, as it would be highly platform dependent. On Linux/UNIX, you can do this with flock or fcntl. I'm not really sure how to do it on Windows.

    On windows, it looks like you have to pass some flags to CreatFile or use LockFileEx (which allows byte range locking).

    Note that, all of these methods work on the underlying OS file descriptors/handles, not with fstreams. You will either need to use the Posix or Windows API to read/write from the file, or wrap the file descriptor/handle in an fstream. This is platform dependent again. I'm sure there is a way to do it, but I don't remember it off the top of my head.

    0 讨论(0)
  • 2020-11-30 11:58

    Expanding on the comment by Casebash:

    To open a file in windows so that other processes cannot write to it use

    file.rdbuf()->open(path, std::ios_base::app, _SH_DENYWR);
    

    _SH_DENYRW will deny both read and write access

    0 讨论(0)
  • 2020-11-30 12:04

    You cannot do it with the standard fstream, you'll have to use platform specific functions.

    On Windows, you can use CreateFile() or LockFileEx(). On Linux, there is flock(), lockf(), and fcntl() (as the previous commenter said).

    If you are using MSVC, you can pass a third parameter to fstream's constructor. See the documentation for Visual Studio 6 or newer versions. Of course it won't work with other compilers and platforms.

    Why do you want to lock others out anyway? There might be a better solution...

    0 讨论(0)
提交回复
热议问题