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;
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.
Splitting the editor (from the tab context menu) allows to have 2 copies of the same file open at the same time.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With