Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an output be followed by an input and vice versa?

Tags:

From APUE

When a file is opened for reading and writing (the plus sign in the type), two restrictions apply.

• Output cannot be directly followed by input without an intervening fflush, fseek, fsetpos, or rewind.

• Input cannot be directly followed by output without an intervening fseek, fsetpos, or rewind, or an input operation that encounters an end of file.

Why "fseek, fsetpos, or rewind" in both cases?

Why "an input operation that encounters an end of file" in the second case?

Thanks.

A similar question for Linux API is Can `read()` be directly followed by `write()` and `write()` by `read()`?

like image 942
Tim Avatar asked Aug 29 '18 03:08

Tim


1 Answers

When working with a FILE stream, there is a single internal buffer used when either reading from or writing to the file.

When switching between reading and writing, that buffer must be cleared before switching modes, otherwise data loss could potentially occur. Each of the operations mentioned above perform the required flushing of the buffer.

like image 62
dbush Avatar answered Sep 28 '22 18:09

dbush