I am with a file using C++ std::fstream and I have difficulty understanding stream positioning. I have extracted a sample code which demonstrate the problem:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::fstream f;
std::string path = "test1.txt";
f.exceptions(std::ios_base::badbit | std::ios_base::failbit | std::ios_base::eofbit);
try {
f.open(path, std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::ate);
} catch (std::ios_base::failure &e) {
std::cout << "Creating new file" << std::endl;
f.open(path, std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
f.write("012345678\n", 10);
return 0;
}
size_t fileSize = f.tellg();
std::cout << fileSize << std::endl;
f.seekg(0);
f.seekp(0);
char dataBuffer[8];
f.read(dataBuffer, 8);
f.write("a\n", 2);
return 0;
}
I expect this code to create and maintain a file which is 10 bytes long, but in fact the file increases by 2 bytes every time the program is ran. Could anyone explain why this is happening?
I am using Apple LLVM compiler:
g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.4.0
EDIT:
It works fine on g++, the strange behavior comes from clang++(clang 5.0 tested).