C++ : Opening a file in non exclusive mode

c++filesystemslinuxwindows

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.

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?

Best Solution

Is there a way to open file in a non-exclusive way,

Yes, using Win32, passing the various FILE_SHARE_Xxxx flags to CreateFile.

is it cross platform?

No, it requires platform-specific code.

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.

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++ 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.