tags:

views:

476

answers:

2

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?

+1  A: 

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.

Zifre
+4  A: 

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, specifying the protection level, but 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...

Hali