Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Windows) Open the same file simultaneously

Tags:

c++

c

windows

I am trying to open a file for writing and reading simultaneously, in windows. I have one program which writes (every one second) to the file and one that reads from it. In unix it works prefectly but it doesn't work in windows (I can't open an already opened file). I open the file with fopen().

How can I solve this problem?

EDIT2:

check out _fsopen it uses FILE *, and set the share flag accordingly.

EDIT:

First of all, some code: this is how I used to open the file

   FILE* f = NULL;
        int res = fopen_s(&f, "c:\\temp\\File1.txt", "w");
        if (res != 0) return;

        while (true) {
            Sleep(1000);
            fprintf_s(f , "Some data");
        }
        fclose(f); 

The read was in other applicaiton, but it did fscanf instead.

The fixed code:

char d[] = "data";


HANDLE h = CreateFile("c:\\temp\\f.txt", GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, CREATE_ALWAYS, /*FILE_ATTRIBUTE_NORMAL*/ FILE_FLAG_WRITE_THROUGH, NULL);

if (h == INVALID_HANDLE_VALUE) return 0;

DWORD bytesW;
while(true) {
    Sleep(100);
        WriteFile(h, d, strlen(d), &bytesW, NULL);
}

CloseHandle(h);
return 0; 
like image 912
Guy L Avatar asked Feb 07 '13 17:02

Guy L


People also ask

Can two processes open the same file at the same time?

During the actual reading and writing, yes. But multiple processes can open the same file at the same time, then write back. It's up to the actual process to ensure they don't do anything nasty.

How do I open the same file twice in Windows?

Splitting the editor (from the tab context menu) allows to have 2 copies of the same file open at the same time.

Can multiple processes read the same file?

Can multiple Java processes read the same file at the same time? Sure they can; and ultimately, it is the role of the OS anyway to ensure that each process/thread reads at its own pace, so you need not worry about it.


Video Answer


1 Answers

Both Windows and Linux have a default way of opening a file, which fopen uses by default.

In Windows, that means blocking (only one process can open a file at a time).

In Linux, it means non-blocking.

fopen is a high-level API. To choose yourself the blocking policy on the file, for Windows you should use OpenFile from WinAPI. In particular, have a look at the OF_SHARE_* flags.

like image 177
utnapistim Avatar answered Oct 03 '22 11:10

utnapistim