C ++ Problem writing to file

My code is:

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

when this C ++ program starts, I have another program that should read this file. The problem is that the file is locked with C ++, and I cannot read it from another program. I know that I need to do something when I write code in some way in a C ++ Program, where it allows sharing. Can someone write exactly what I need. I killed it to death and still can't get it to work.

Some say close the file before another program reads it. I can not do this, the file must be open.

thanks

+4
source share
4 answers

You need to open the file with access 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 sharing mode as nProt :

  • filebuf::sh_compat : filebuf::sh_compat Mode
  • filebuf::sh_none : exclusive mode; without exchange
  • filebuf::sh_read : read sections allowed
  • filebuf::sh_write : write allowed.

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

+1
source

Exchange will be controlled at the OS level. So you need to take a look at the API for your OS and figure out how to enable read-write sharing.

Note: you probably won’t get the desired results, because there will be problems with caching and buffering, and what you think was written to the file does not actually exist.

If you want to exchange information between two processes, use named pipes or sockets. Both are available for almost every OS.

0
source

Use filebuf::sh_write when opening a file.

0
source

Another option is to use sockets. Have a look at this stackoverflow question: Is there a way for multiple processes to share a listening socket?

0
source

All Articles