I'd like to open file, read it's content and then fully override it. Apart from that I'd like this file to be locked by process during whole procedure. This is the idea I came with:
fopen_s(&fp, file_path, "rb");
...
fclose(fp);
fopen_s(&fp, file_path, "wb+");
...
fclose(fp);
But this solution generates small time window when file is not locked by process. That's the second idea:
fopen_s(&fp, file_path, "rb");
...
freopen_s(&fp, file_path, "wb+", fp);
...
fclose(fp);
Here, I could not find information whether freopen_s
preserves file lock but I suppose that it does not.
Third and last idea I came with is to open file in ab+
mode:
fopen_s(&fp, file_path, "ab+");
// read content
fseek(fp, 0L, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
fread(buffer, sizeof(char), file_size, fp);
// TODO: override file
fseek(fp, 0L, SEEK_SET);
fwrite("hello", 1, 5); // does not work - appends to end of file
fclose(fp);
This solution has the best potential but I can't make it override file content in any way - every method that writes file content appends instead of writing to beggining.
Is there any option to improve one of solution mentioned above or is there any other way to achieve my goal? Note that I'd not like to use WinAPI calls.