std::ofstream 且 std::ate 最后未打开

std::ofstream with std::ate not opening at end

我正在尝试打开一个文件进行输出并附加到它。附加到它之后,我想将我的输出位置移动到文件中的其他位置并 overwrite 现有数据。据我了解,std::ios_base::appforce 所有写入都位于文件末尾,而 不是我想做什么。因此,我相信 std::ios_base::ate 是传递给 std::ofstream::open() 的正确标志。但是,它似乎没有按预期工作:

// g++ test.cpp
// clang++ test.cpp
// with and without -std=c++11
#include <iostream>
#include <fstream>

int main() {
    std::streampos fin, at;
    {
        std::ofstream initial;
        initial.open("test", std::ios_base::out | std::ios_base::binary);
        if ( not initial.good() ) {
            std::cerr << "initial bad open" << std::endl;
            return 1;
        }
        int b = 100;
        initial.write((char*)&b, sizeof(b));
        initial.flush();
        if ( not initial.good() ) {
            std::cerr << "initial write bad" << std::endl;
            return 1;
        }
        fin = initial.tellp();
    }
    {
        std::ofstream check;
        check.open("test", std::ios_base::out | std::ios_base::binary | std::ios_base::ate);
        if ( not check.good() ) {
            std::cerr << "check bad open" << std::endl;
            return 1;
        }
        at = check.tellp();
        if ( fin != at ) {
            std::cerr << "opened at wrong position!\nfin:\t" << fin << "\n" << "at:\t" << at << std::endl;
            return 1;
        }
        int bb = 200;
        check.write((char*)&bb, sizeof(bb));
        check.flush();
        if ( not check.good() ) {
            std::cerr << "check write bad" << std::endl;
            return 1;
        }
        at = check.tellp();
    }
    if ( (fin + std::streampos(sizeof(int))) != at ) {
        std::cerr << "overwrite?\nfin:\t" << fin << "\n" << "at:\t" << at << std::endl;
        return 1;
    }
    return 0;
}

特别是,似乎 std::ios_base::ate 而不是 将初始输出指针移动到上面示例的末尾。显然这会导致第一次写入覆盖文件的开头(这就是我的麻烦所在)。

似乎要么实现不正确,要么cplusplus.com is incorrect ("The output position starts at the end of the file.") and cppreference.com不明确("seek to the end of stream immediately after open":哪个流?​​)。

显然有一个简单的解决方法:只需使用 stream.seekp(0, std::ios_base::end).

所以我的问题是:我的代码不正确吗?执行不正确?参考站点是否不正确?任何见解将不胜感激。

从下面N4296的图表可以看出[filebuf.members]

组合 binary | out 将以 stdio 相当于 "wb" 的方式打开文件,这将 truncate to zero length or create binary file for writing (N1570 7.21.5.2).

对于 ofstream,这听起来违反直觉,如果您不希望文件被截断,则需要添加 in 标志,或者如果您不希望文件被截断,则需要添加 app希望避免截断并在每次写入时查找文件末尾。

额外提示:与 fstream 不同,ifstreamofstream 将自动或 std::ios_base::instd::ios_base::out 分别与您提供给构造函数的任何标志或至 open。您还可以使用对象本身来访问标志:

std::ofstream check("test", check.in | check.binary | check.ate);

good的检查也可以缩短为if (!initial)