[Search for users] [Overall Top Noters] [List of all Conferences] [Download this site]

Conference turris::c_plus_plus

Title:C++
Notice:Read 1.* and use keywords (e.g. SHOW KEY/FULL KIT_CXX_VAX_VMS)
Moderator:DECCXX::AMARTIN
Created:Fri Nov 06 1987
Last Modified:Thu Jun 05 1997
Last Successful Update:Fri Jun 06 1997
Number of topics:3604
Total number of notes:18242

3418.0. "lock a file ??" by NETRIX::"[email protected]" (rick) Thu Jan 30 1997 21:40

Is there a way to lock a file that has been opened as follows:

ofstream os;

os.open("file.txt", ios::trunc);

What I want is a way for two cooperating processes to open and write
to a file. When one has it open for write and locks it, the other
cannot open it. In C I would do this by opening the file and
using flock() on the file descriptor.  

Any ideas?

Thanks, Rick

[Posted by WWW Notes gateway]
T.RTitleUserPersonal
Name
DateLines
3418.1SPECXN::DERAMODan D'EramoFri Jan 31 1997 11:1313
>Is there a way to lock a file that has been opened as follows:
>
>ofstream os;
>
>os.open("file.txt", ios::trunc);

        I don't know about a file opened that particular way.  But you
        can call the C run-time library open() function, then use
        flock() on the file descriptor, then use the ofstream::attach()
        member function to "attach" the ofstream object to the file
        descriptor.
        
        Dan
3418.2.1 is correct, this is how you would do it...DECC::J_WARDFri Jan 31 1997 11:1916
#include <fstream.h>
#include <fcntl.h>

main() {

	// open it the C way
	int fd = open("file.txt",O_TRUNC, 0644);

	ofstream os;
	// use attach
	os.attach(fd);

	// now you have the file descriptor...

}