fstream lock question

R

Rob Kreger

This code works on Windows XP with VC7.1 stl(sxl 3.08 from
dinkumware.)

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <io.h>
#include <fstream>
#include <sys/locking.h>


int _tmain(int argc, _TCHAR* argv[])
{
FILE* lFile = fopen("MyFile","w");
int lfd = _fileno( lFile );
while(1)
{
int lReturn = _locking(lfd,LK_NBLCK,10000);
if(lReturn != -1)
break;
if(errno != EACCES )
throw("Lock failure");
}

std::filebuf lfilebuf(lFile);
std::eek:stream lostream(&lfilebuf);
lostream << "some text" << std::endl;
_locking(lfd,LK_UNLCK,10000);
fclose(lFile);
return 0;
}

Is there a better to way to lock a file with c++?
How can I implement a read and write lock for the same file?

The problem I have with this code is it is not portable? Is there a
portable solution?

I have many objects that overload << and I need to use a stream.

Why doesn't the ansi c++ standard address this issue, the
functionality, of protecting files, seem very trivial to me!!!

Any help would be greatly appreciated.

Rob Kreger
 
J

Jack Klein

This code works on Windows XP with VC7.1 stl(sxl 3.08 from
dinkumware.)

#include "stdafx.h"

This is not a C++ language header.
#include <iostream>
#include <stdio.h>
#include <io.h>

This is not a C++ language header.
#include <fstream>
#include <sys/locking.h>

This is not a C++ language header.
int _tmain(int argc, _TCHAR* argv[])

This does not appear to be a valid signature for main() in a hosted
environment.
{
FILE* lFile = fopen("MyFile","w");
int lfd = _fileno( lFile );

No such function as _fileno() in the C++ language.

[snip]

You need to take this to a Windows programming group, or one of
Microsoft's support groups for Visual C++. It is not a language
question and your code is far too loaded with non-standard headers and
non-standard code for it to be topical here.

There is no such thing as file locking in C++. File locking is a
feature of operating systems, and it varies from one OS to the next.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top