0

I have a save file containing a stream of program events. The program may read the file and execute the events to restore a previous state (say between program invocations). After that any new events are appended to this file.

I could open the file once as read-write (fopen rw), not exposing the usage pattern.

But I wonder if there are any benefits of opening it as read-only at first (fopen r) and later re-opening it as append (freopen a). Would there be any appearent difference?

Andreas
  • 5,086
  • 3
  • 16
  • 36
  • I depends what you mean by benefits. If the file is open as read only then another process can safely read it too. Or do you mean is it faster to open as read only? That probably depends on the OS. You can run a benchmark for your specific task. My guess is there is no difference in performance. – Barmak Shemirani Nov 04 '17 at 21:34
  • @BarmakShemirani I mean benefits in the most broad sense. Performance, usage, function... Anything that might promote one over the other. I´m leaning towards reopening because it more accurately correspond what I do to the file in different stages of my program (usage). – Andreas Nov 05 '17 at 10:33

2 Answers2

1

No there are no specific benefits of opening the file as Read Only and then reopening in Append mode. If you require changes in files during program execution than better if you open it in as per mode.

ayush garg
  • 86
  • 6
1

In your case there may not be any specific benefits, but primary use of freopen is to change the file associated with standard text stream (stdin, stdout, stderr). It may effect the readability of your code if you use if on normal files. In your case you first open in read-only mode, but if you are opening the stream as output there are few things about freopen that we need to keep in mind.

  1. On Linux, freopen may also fail and set errno to EBUSY when the kernel structure for the old file descriptor was not initialized completely before freopen was called
  2. freopen should not be used on output streams because it ignores errors while closing the old file descriptor.

Read about freopen and possible error conditions with fclose in GNU manual: https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html#Opening-Streams

Ravi
  • 986
  • 12
  • 18