MISRA C++:2023 Rule 30.0.2
Reads and writes on the same file stream shall be separated by a positioning operation
Since R2024b
Description
Rule Definition
Reads and writes on the same file stream shall be separated by a positioning operation.
Rationale
If you use a file stream for both reading and writing, between read and write operations on the stream, you must perform a stream repositioning operation.
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 the C FILE*
abstraction. 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 following an input (or vice versa), you must first reposition the pointer in the file stream; otherwise, the behavior is undefined.
Polyspace Implementation
The rule checker reports a violation when you perform an output operation on a file stream following an input operation or vice versa, without an intermediate repositioning of the file stream. The checker detects issues in file operations using one of these file pointers:
A
FILE*
pointer (for files opened using functions such asfopen()
).An
std::basic_filebuf
object (for files opened using functions such asstd::fstream()
)
Depending on whether you use a FILE*
pointer or an std::basic_filebuf
object, you can reset the position in the file stream using one of these functions:
For
std::basic_filebuf
objects, you can reposition a file stream using methods such asstd::fstream<>::seekp()
orstd::fstream<>::seekg()
.For
FILE*
pointers, you can call 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)..
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 |
Version History
Introduced in R2024b