Reputation: 23
I have two programs that read and write to the same file. One appends data, the other clears the file and then rewrites all data.
The two programs interact fine on the same computer but when I run one on another computer and open the file over my local network my append doesn't seem to get through in time.
My process is as follows:
Program 1:
Open file with
handle = CreateFile(str.c_str(),
FILE_READ_DATA|FILE_APPEND_DATA,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
Write data using:
WriteFile(handle, line, strlen(line), &Written, NULL);
Close file using:
CloseHandle(handle);
Program 2:
Open file with:
handle = CreateFile(str.c_str(),
FILE_READ_DATA|FILE_WRITE_DATA,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
If file size is different than last time it was read using:
size = GetFileSize(handle, &size_high);
(I'm only looking at size here, size_high is ignored since file sizes are relatively small)) then close the file, open it using FILE_READ_DATA flag, reload data and then retry from previous step.
Otherwise clear file data using:
SetFilePointer(handle,0,NULL,FILE_BEGIN);
SetEndOfFile(handle);
Rewrite all data using:
WriteFile(handle, line, strlen(line), &Written, NULL);
Close file using:
CloseHandle(handle)
Program 1 prompts the user to retry the save if the file is locked by another program. Program 2 retries a couple of times if the file is locked by another program.
It looks like when accessing the file over the network my append operation in program 1 is not being picked up by program 2 before it clears and rewrites its data. I've tried opening the file in program 1 with FILE_FLAG_WRITE_THROUGH flag set and also using FlushFileBuffers(handle) before closing the file with no luck.
Is there something I'm missing in this process?
I am coding in Embarcadero C++ Studio if that helps.
Thanks for your time.
Upvotes: 2
Views: 1102
Reputation: 612954
File locking is known not to work reliably and robustly for file access to network shares. Simply put, you need to find another mechanism to implement mutual exclusion. For example, use a client/server database design.
Upvotes: 4