CERT.FIO.NO_POSITIONING
Missing positioning call between file-stream output and input
When alternately inputting and outputting on the same file stream, there should be an intervening positioning call such as seekg() or seekp().
Vulnerability and risk
Receiving input from a file stream directly after output, or output directly after input, without an intervening positioning call can lead to undefined behavior.
Mitigation and prevention
Add a positioning call between input and output operations on the same file stream.
Vulnerable code example
#include <fstream>
#include <string>
void f(const std::string &fileName) {
std::fstream file(fileName);
if (!file.is_open()) {
return;
}
file << "Output some data";
std::string str;
file >> str; // CERT.FIO.NO_POSITIONING
}
In this noncompliant example, the code writes to a file stream and then reads from the same stream without an intervening positioning call; therefore, Klocwork reports a CERT.FIO.NO_POSITIONING defect.
Fixed code example
#include <fstream>
#include <string>
void f(const std::string &fileName) {
std::fstream file(fileName);
if (!file.is_open()) {
return;
}
file << "Output some data";
file.seekg(0, std::ios::beg);
std::string str;
file >> str; // no CERT.FIO.NO_POSITIONING
}
In this fixed example, seekg() repositions the file stream before the read, so Klocwork does not report a defect.