问题
I have an application that creates a text log file using an std::ofstream
using std::ofstream::app
to create it. This application is writing logs often, sometimes only milliseconds apart.
I want to write a second application that reads in and analyses this log file whilst the first application is still writing to it
I have some working code, using ifstream
, that loads & processes a standalone text log file, but this code fails when I try to use it on the text log file that is currently being written to with "The process cannot access the file because it is being used by another process."
How can I adjust my log reader to allow me to read the text file currently being written to (which Notepad++ is able to do on the same file!)?
回答1:
On Windows you can pass a third parameter to the stream constructors / open
to allow sharing, e.g.
std::ofstream of("path", of.app, _SH_DENYNO);
(int)ios_base::_Openprot
is passed by default which is an enum
set to _OPENPROT
, which is in turn defined as _SH_DENYNO
so it should already work without specifying the flag, I'm not really sure why it doesn't in your case, have you tried following the definitions in VS or debugging the code?
reference:
http://msdn.microsoft.com/en-us/library/y1et11xw(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/kexhtshc(v=vs.110).aspx
来源:https://stackoverflow.com/questions/25176714/how-to-read-a-text-file-that-is-already-in-use-windows-c