1

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.

elklepo
  • 509
  • 4
  • 17

1 Answers1

0

According to this post - How do I lock files using fopen()? - flock may help you

tscheppe
  • 588
  • 5
  • 18
  • `fopen()` on Windows locks file by default, there is no need to call `flock()`, it does not even exist in stdlib on Windows. – elklepo Aug 14 '19 at 12:51
  • according to [link](https://en.cppreference.com/w/c/io/freopen) `freopen_s` closes an reopens the file and also releases and reaquires the the lock. Why don't you just open the file with write access if you know you are going to write on in? – tscheppe Aug 14 '19 at 14:06
  • besause, as I mentioned in third example, I'm unable to read file content and fully rewrite it within single `fopen()`. – elklepo Aug 14 '19 at 14:28
  • @Klepak with the flag "rb+" you can read and write to the file. with "ab+" like you did you just append something. So you can try your third example with this flag. Another possibilty could be open it with "rb+" read everything, truncate the file [link](http://man7.org/linux/man-pages/man2/truncate.2.html) and the write on it. – tscheppe Aug 16 '19 at 09:32