简体   繁体   English

如何在C ++中写入文件而不锁定它?

[英]How to write to file in C++ without locking it?

C++ In Windows 7. When writing to my log file, i sometimes set a breakpoint, or the program gets stuck at something. Windows 7中的C ++。在写入日志文件时,有时会设置断点,否则程序会卡在某些东西上。 When i try too peek in my logfile from another program it says "The file cannot be opened because it is in use by another process". 当我尝试从其他程序中查看我的日志文件时,它说“文件无法打开,因为它正在被另一个进程使用”。 Well thats true, however I've worked with other programs that still allows reading from a logfile while they are writing to it, so I know it should be possible. 是的,没错,但是我与其他程序一起工作,这些程序仍然允许在日志文件写入日志文件时进行读取,因此我知道这是可能的。 Tried the _fsopen and unlocking the file but without success. 尝试_fsopen并解锁文件,但未成功。

FILE* logFile;
//fopen_s(&logFile, "log.log", "w");
logFile = _fsopen("log.log", "w", _SH_DENYNO);

if (!logFile)
    throw "fopen";

_unlock_file(logFile);

If you have the log-file open with full sharing-mode, others are still stopped from opening for exclusive access, or with deny-write. 如果您以完全共享模式打开了日志文件,则仍然会阻止其他文件打开以进行独占访问或拒绝写入。

Seems the second program wants more access than would be compatible . 似乎第二个程序需要比兼容更多的访问

Also, I guess you only want to append to the log, use mode "a" instead of "w" . 另外,我猜您只想追加到日志,请使用模式“ a”而不是“ w”

Last, do not call _unlock_file unless you called _lock_file on the same file previously . 最后, 除非您_lock_file在同一文件_lock_file _unlock_file否则请不要调用_unlock_file


There is a way to do what you want though: 有一种方法可以执行您想要的操作:

Open your file without any access, and then use Opportunistic Locks . 无需任何访问即可打开文件,然后使用“ 机会锁定”

Raymond Chen's blog The Old New Thing also has a nice example: http://blogs.msdn.com/b/oldnewthing/archive/2013/04/15/10410965.aspx Raymond Chen的博客The Old New Thing也有一个很好的例子: http : //blogs.msdn.com/b/oldnewthing/archive/2013/04/15/10410965.aspx

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

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