AUTOSAR C++14 Rule A27-0-3
Alternate input and output operations on a file stream shall not be used without an intervening flush or positioning call
Since R2020b
Description
Rule Definition
Alternate input and output operations on a file stream shall not be used without an intervening flush or positioning call.
Rationale
Using a file stream for alternating input and output without using stream repositioning statements between read and write operations may lead to undefined behavior.
When you open a file stream using a function such as std::fstream()
, an std::basic_filebuf
object is created to track the position in the file stream where the next read or write operation will occur. The implementation of this object uses a C FILE*
pointer. According to the C standard, a single FILE*
pointer can be used to perform both input and output operations on a file stream. However, before you perform
an output operation followed by an input operation or an input operation followed by an output operation, you must first reposition the pointer in the file stream. Failing to do so can result in undefined behavior.
Polyspace Implementation
The rule checker reports a violation when you perform an output operation on a file stream followed by an input operation or an input operation followed by an output operation, without an intermediate repositioning of the file stream. The checker detects issues in file operations using one of the following file stream representations:
A
FILE*
pointer for files opened using functions such asfopen()
An
std::basic_filebuf
object for files opened using functions such asstd::fstream()
Reset the position in the file stream in one of these ways:
For
FILE*
pointers, use a file positioning function such asfseek()
orfsetpos()
between output and input operations or call thefflush()
function to flush the output buffer between an output and a subsequent input operation.For
std::basic_filebuf
objects, use file stream positioning methods such asseekp()
orseekg()
.
Troubleshooting
If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Input/output library |
Category: Required, Automated |