Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 291
sofr Avatar asked May 08 '09 13:05

sofr


People also ask

What is opening and closing a file in C++?

In order to perform file handling, some general functions which are used are as follows: open(): This function helps to create a file and open the file in different modes, like input operations, output operations, binary mode, etc. close(): This function helps to close an existing file.


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

like image 170
Hali Avatar answered Oct 23 '22 21:10

Hali