2

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).

llllllllll
  • 16,169
  • 4
  • 31
  • 54
user223662
  • 29
  • 4
  • I can't reproduce this. On the first run it says "Creating new file" and on each subsequent run "10". Even after several runs the file is 10 bytes long as expected. – The Vee Feb 08 '18 at 13:08
  • Are you sure you recompiled this exact version of the program? – The Vee Feb 08 '18 at 13:12
  • Which compiler and OS? – Mark Ransom Feb 08 '18 at 13:26
  • This behaviour would be indicative of [`std::ios_base::app` instead of `std::ios_base::ate`](https://stackoverflow.com/questions/10359702/c-filehandling-difference-between-iosapp-and-iosate). I don't think C++ allows the latter to behave like the former. – The Vee Feb 08 '18 at 13:54
  • I copy-pasted the source from this webpage into a new file and compiled it to make sure it is the same. The behaviour doesn't change. I have added information about compiler into question. – user223662 Feb 08 '18 at 14:23
  • @user223662 It's probably a clang bug, you can add an empty `f.tellg()` before `f.write()` to remedy. But I don't know exactly whether it's considered a bug. Titles and tags updated. – llllllllll Feb 08 '18 at 14:34

0 Answers0