我使用的是一个使用C std :: fstream的文件,我很难理解流的定位 . 我已经提取了一个演示问题的示例代码:

#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;
}

我希望这段代码能够创建和维护一个10字节长的文件,但实际上每次运行程序时文件都会增加2个字节 . 任何人都可以解释为什么会这样吗?

我正在使用Apple LLVM编译器:
g -v
配置为: - prefix = / Library / Developer / CommandLineTools / usr --with-gxx-include-dir = / usr / include / c /4.2.1
Apple LLVM 9.0.0版(clang-900.0.39.2)
目标:x86_64-apple-darwin17.4.0

EDIT:

它在g上工作正常,奇怪的行为来自clang(clang 5.0测试) .