ios_base::ate and tellp()

ios_base::ate and tellp()

本文关键字:tellp and ate base ios      更新时间:2023-10-16
#include <fstream>
#include <iostream> 
int main() 
{ 
    const char* fileName = "out1"; 
    std::ofstream fs1(fileName); 
    fs1 << "AAAAAAAAAAAn"; 
    std::cout << fs1.tellp() << std::endl; 
    fs1.close(); 
    std::ofstream fs2(fileName, std::ios_base::ate); 
    std::cout << fs2.tellp() << std::endl; 
    fs2.close(); 
    return 0;   
}   
GCC 版本 4.4.6

20120305 (Red Hat 4.4.6-4) (GCC)

g++ 文件02.cpp

.

/a.out

120

为什么 fs2.tellp() 打印 0,而不是 12?

当您打开一个文件进行输出时 std::ofstream ,除非您同时设置 std::ios_base::instd::ios_base::out ,或者在 mode 参数中设置std::ios_base::app,否则该文件将被截断。

传递给 std::ofstreamstd::ifstream 构造函数的 mode 参数将转发到std::filebuf::open成员函数。它的值确定如何根据映射到 mode 参数到 C 库函数fopen的相应行为来打开文件。此映射考虑除 std::ios_base::ate 之外的所有标志集。总之,映射如下:

标志组合:输入输出截断应用程序 |打开模式                        + "w"                        + + "a"                                  + "a"                        + + "w"                   + "r"                   + + "r+"                   + + + + "w+"                   + + + + "A+"                   + + "A+"

(C++03 省略了设置了appout未设置的行;这些行现在等效于设置了 appout的行。

此外,如果设置了std::ios_base::binary,则会将b追加到fopen模式等效项。

如果传递的标志组合(忽略std::ios_base::ate)与这些组合之一不匹配,则打开应该失败。

请注意,fopen截断模式 "w""w+" 的文件。

std::ios_base::ate会导致在打开文件时将位置设置为文件的末尾。仅当 mode 参数的其余部分不会导致打开的文件被截断并且文件已存在且大小为非零时,这才有效。

再次打开文件进行写入时未提供 out 标志。这样做:

std::ofstream fs2(fileName, std::ios_base::out | std::ios_base::ate);