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?
-
I need to read from the file and change lines according to the content. I want to avoid changes in the file while I'm reading and writing to it (have latest data & don't override) I implented it using fstream, do I need to change the whole code to using handles and buffers (readfile) or can I get a Handle from fstream? I had trouble with readfile and writefile because I need to read line by line and write so . (with fstream I used getline function. fstream fs(path) while (! file.eof() ) getline (fs,line); do something... fs.write(str, str.size()); fs.clear(); fs.close(); – sofr May 08 '09 at 15:21
-
Do you want to protect your file from another instance of your program, or from a different program? For the first, an easy solution is to use lock files/directories - most programs do it this way. For the second, I've never seen it happening - if you really need it, see my answer. – Hali May 10 '09 at 02:23
3 Answers
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...
-
1[This thread](http://stackoverflow.com/questions/4435091/sh-none-is-not-a-member-of-stdbasic-filebuf-elem-traits/4435481#4435481) provides more information on using `fstream` – Casebash Dec 14 '10 at 03:29
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

- 48,469
- 17
- 71
- 80
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 fstream
s. 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.

- 26,504
- 11
- 85
- 105
-
5I know this is 10 years old, but how can be locking a file more platform-dependent then any other file operations that use also platform-specific syscalls? – Zaffy Jun 10 '19 at 14:24