简体   繁体   English

如何读取已在使用的文本文件(Windows C ++)

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

I have an application that creates a text log file using an std::ofstream using std::ofstream::app to create it. 我有一个应用程序,使用std::ofstream创建一个文本日志文件,使用std::ofstream::app来创建它。 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." 我有一些工作代码,使用ifstream ,加载和处理一个独立的文本日志文件,但当我尝试在当前正在写入的文本日志文件上使用它时,此代码失败“进程无法访问该文件,因为它被另一个进程使用。“

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!)? 如何调整我的日志阅读器以允许我读取当前正在写入的文本文件(Notepad ++能够对同一文件执行哪些操作!)?

On Windows you can pass a third parameter to the stream constructors / open to allow sharing, eg 在Windows上,您可以将第三个参数传递给流构造函数/ open以允许共享,例如

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? (int)ios_base::_Openprot默认情况下传递_OPENPROT ,这是一个设置为_OPENPROTenum ,然后定义为_SH_DENYNO所以它应该已经工作而没有指定标志,我不确定为什么它不在你的情况下,您是否尝试过遵循VS中的定义或调试代码?

reference: 参考:

http://msdn.microsoft.com/en-us/library/y1et11xw(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/y1et11xw(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/kexhtshc(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/kexhtshc(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM