ios_base::ate and tellp()
ios_base::ate and tellp()
#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::in
和 std::ios_base::out
,或者在 mode 参数中设置std::ios_base::app
,否则该文件将被截断。
传递给 std::ofstream
和 std::ifstream
构造函数的 mode 参数将转发到std::filebuf::open
成员函数。它的值确定如何根据映射到 mode 参数到 C 库函数fopen
的相应行为来打开文件。此映射考虑除 std::ios_base::ate
之外的所有标志集。总之,映射如下:
标志组合:输入输出截断应用程序 |打开模式 + "w" + + "a" + "a" + + "w" + "r" + + "r+" + + + + "w+" + + + + "A+" + + "A+"
(C++03 省略了设置了app
但out
未设置的行;这些行现在等效于设置了 app
和out
的行。
此外,如果设置了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);
相关文章:
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么tellp()给出-1
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 为什么 Clang 不允许"and"作为函数名称?
- 位阵列上的快速AND运算
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- BoostPython and CMake
- OpenSSL BIO and SSL_read
- Gurobi GRBModel and GRBmodel in C++
- std::visit and std::variant usage
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- Directx12 and keystrokes
- different between int **arr =new int [ n]; and int a[i][j]?
- C++ getenv and setenv
- Inference pytorch C++ with alexnet and cv::imread image
- Visual Studio 2019 C++ and std::filesystem
- 保证逻辑 AND 表达式中的函数调用
- python ctypes and C++ pointers
- C++ const char with .begin() and .end()
- ios_base::ate and tellp()