Rule A27-0-3 (required, implementation, automated)
Alternate input and output operations on a file stream shall not be used without an intervening flush or positioning call.
Rationale
There are following restrictions on reading and writing operations called for an object of class basic_filebuf<charT, traits>: output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind).
input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. It is recommended to use a file stream either for output ( std::ofstream) or input(std:: ifstream) and not for both in the same context. This avoids the mentioned problem altogether.
Example
// $Id: A27-0-3.cpp 311495 2018-03-13 13:02:54Z michal.szczepankiewicz $
#include <fstream>
#include <string>
int main(void)
{
std::fstream f("testfile");
f << "Output";
std::string str1;
f >> str1; // non-compliant
f << "More output";
std::string str2;
f.seekg(0, std::ios::beg);
f >> str2; //compliant
return 0;
}
See also
SEI CERT C++ Coding Standard [10]: FIO39-C: Do not alternately input and output from a stream without an intervening flush or positioning call SEI CERT C++ Coding Standard [10]: FIO50-CPP: Do not alternately input and output from a file stream without an intervening positioning call