4

My Code:

std::ofstream m_myfile,

m_myfile.open ("zLog.txt");
m_myfile << "Writing this to a file " << " and this " << endl;

when this C++ Program runs, I have another program that needs to read this file. The problem is that the file is locked by C++ and I cannot read it from the other program. I know there is something I have to do where I write the code someway in the C++ Program where it allows sharing. Can someone write exactly what I need. I have googled this to death and still cannot get this to work.

Some people say close the file, before the other program reads it. I cannot do this, the file needs to be open.

Brian
  • 41
  • 2
  • What do you mean when you say that "the file is locked?" What does the other program attempt to do (with code), what errors/exceptions/symptoms does it encounter, and what did you expect instead? – pilcrow Sep 28 '10 at 15:20
  • Are you trying to implement pipes? Do you want to read and write to the file simultaneously or first write and then read? For second option you could create locking file "zlog.lck" by program that writes the file and make checks for it existence in the one that need to read the locked file. – erjot Sep 28 '10 at 15:24
  • Why does the file need to remain open and what operating system are you targetting as this will have an impact? – ChrisBD Sep 28 '10 at 15:24
  • possible duplicate of [C++ : Opening a file in non exclusive mode](http://stackoverflow.com/questions/27700/c-opening-a-file-in-non-exclusive-mode) – luke Aug 21 '12 at 11:23

4 Answers4

1

You need to open the file with sharing enabled. Use the following overload of the open method:

void open(const char *szName, int nMode = ios::out, int nProt = filebuf::openprot);

and pass the appropriate share mode as nProt:

  • filebuf::sh_compat: Compatibility share mode
  • filebuf::sh_none: Exclusive mode; no sharing
  • filebuf::sh_read: Read sharing allowed
  • filebuf::sh_write: Write sharing allowed

There is also an overload of the ofstream constructor that takes the same arguments.

Richard Cook
  • 32,523
  • 5
  • 46
  • 71
0

The sharing is going to be controlled at the OS level. So you need to look at the API for your OS and figure out how to turn read-write sharing on.

Note: you still probably won't get the results you want because there will be caching and buffering issues and what you think was written to the file may not actually be there.

If you want to share information between two processes, use named pipes or sockets. Both are available on just about every OS.

miked
  • 3,458
  • 1
  • 22
  • 25
0

Use filebuf::sh_write while opening the file.

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
0

Other option is to use sockets. Check out this stackoverflow question: Is there a way for multiple processes to share a listening socket?

Community
  • 1
  • 1
yasouser
  • 5,113
  • 2
  • 27
  • 41