How to read a text file that is already in use (Windows C++)

那年仲夏 提交于 2020-01-05 12:33:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!