Andreas
Andreas

Reputation: 5301

Any reason to reopen as "write-append" after "read-only"?

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?

Upvotes: 0

Views: 444

Answers (2)

Ravi
Ravi

Reputation: 1066

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

Upvotes: 1

ayush garg
ayush garg

Reputation: 108

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.

Upvotes: 1

Related Questions