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

前端 未结 3 723
被撕碎了的回忆
被撕碎了的回忆 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.

提交回复
热议问题