1

I have a file that I'm writing data to, using the functions in cstdio. I want to make sure the file has successfully been written to file without any interruptions, so I know what to expect from the file when I later read from it. The way I aim to do that, is by first writing 8 bytes worth of zeroed out data to the very beginning of the file, writing the file as normal, and then as a last step, rewinding the file and overwriting those first 8 bytes with a specific signature to denote that the file has been completed and well-formed.

My question is, what is the best way to edit those first 8 bytes in place?

With fopen(), what would be the appropriate opening mode (the second argument) to use?

Is it safe to just rewind() to the beginning and use fwrite(), or is there a specific function special to the act of overwriting?

Anne Quinn
  • 10,856
  • 7
  • 40
  • 83
  • FYI: Mode `"rb+"` will allow you to `fopen()` for read/write. And make sure if you immediately follow a `fwrite()` with an `fread()` you wedge a flush in between. – WhozCraig Aug 17 '13 at 07:13
  • @whozCraig That sounds about right, though I'm creating the file in this case. Would "wb+" work similarly? – Anne Quinn Aug 17 '13 at 07:30
  • 1
    yes, that should be fine. It will truncate the file if it exists. If that is the intention, it should work for you. – WhozCraig Aug 17 '13 at 08:05

1 Answers1

1

WhozCraig is right. Using wb+ is completely fine as well as rewind is.

You can also take a look at file locking, which ensures that:

  • no one can read/write the file while you are holding exclusive lock
  • no one can write the file while you are holding shared lock
Zaffy
  • 14,842
  • 8
  • 42
  • 70