C ++:以非独占模式打开文件 [英] C++ : Opening a file in non exclusive mode
问题描述
我必须开发一个解析日志文件并将特定数据发送到服务器的应用程序。它必须在Linux和Windows上运行。
I have to develop an application which parses a log file and sends specific data to a server. It has to run on both Linux and Windows.
当我想测试日志滚动系统时会出现这个问题(它会在创建一个名称相同的名称后加上.1)。在Windows上(还没有在Linux上测试)即使我在输入模式(ios :: in)中打开它,我也无法重命名我使用std :: ifstream()(独占访问?)打开的文件。
The problem appears when I want to test the log rolling system (which appends .1 to the name of the creates a new one with the same name). On Windows (haven't tested yet on Linux) I can't rename a file that I have opened with std::ifstream() (exclusive access?) even if I open it in "input mode" (ios::in).
是否有跨平台方式以非排他方式打开文件?
Is there a cross-platform way to open file in a non-exclusive way?
推荐答案
是否有以非排他方式打开文件的方法,
Is there a way to open file in a non-exclusive way,
是,使用Win32,将各种FILE_SHARE_Xxxx标记传递到CreateFile。
Yes, using Win32, passing the various FILE_SHARE_Xxxx flags to CreateFile.
是跨平台吗?
is it cross platform?
不,它需要特定于平台的代码。
No, it requires platform-specific code.
由于令人烦恼的向后兼容性问题假设没有什么可以从它们下面删除一个文件,即他们可以fclose()和然后fopen()没有任何东西出现; Win16保留这个假设,使移植DOS应用程序更容易,Win32保留这个假设,使
Due to annoying backwards compatibility concerns (DOS applications, being single-tasking, assume that nothing can delete a file out from under them, i.e. that they can fclose() and then fopen() without anything going amiss; Win16 preserved this assumption to make porting DOS applications easier, Win32 preserved this assumption to make porting Win16 applications easier, and it's awful), Windows defaults to opening files exclusively.
底层操作系统基础架构支持删除/重命名打开的文件(虽然我相信它有限制内存映射文件不能被删除,我认为不是在* nix上找到的限制),但默认开启语义不。
The underlying OS infrastructure supports deleting/renaming open files (although I believe it does have the restriction that memory-mapped files cannot be deleted, which I think isn't a restriction found on *nix), but the default opening semantics do not.
C ++没有任何这样的概念; C ++操作环境与DOS操作环境相同 - 没有其他应用程序同时运行,因此不需要控制文件共享。
C++ has no notion of any of this; the C++ operating environment is much the same as the DOS operating environment--no other applications running concurrently, so no need to control file sharing.
这篇关于C ++:以非独占模式打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!