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

Solution 1:

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...

Solution 2:

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