tags:

views:

85

answers:

5

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.

Thanks

A: 

See this SO question.

luke
+1  A: 

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
A: 

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
A: 

Use filebuf::sh_write while opening the file.

Chubsdad
A: 

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

anand.arumug