为什么ofstream( "log.txt" , ios::app|ios::trunc);总是失败?
Why does ofstream("log.txt", ios::app|ios::trunc); always fail?
以下代码是在Windows 7 x64上使用VC++2012年11月CTP编译的。
#include <fstream>
using namespace std;
int main()
{
ofstream fout("log.txt", ios::app|ios::trunc);
if (!fout)
{
cout << "An error occurred!" << endl; // Always go here! Why?
}
}
cppreference.com网站没有说ios::app
不能与ios::trunc
组合。
ios::app
和ios::trunc
的确切语义是什么?
这些标志传递到的filebuf
构造函数†具有基于C++11:中表132中定义的那些标志的行为
+-----------------------------------+-------------------+
| ios_base flag combination | stdio equivalent |
| binary in out trunc app | |
+-----------------------------------+-------------------+
| + | "w" |
| + + | "a" |
| + | "a" |
| + + | "w" |
| + | "r" |
| + + | "r+" |
| + + + | "w+" |
| + + + | "a+" |
| + + | "a+" |
+-----------------------------------+-------------------+
| + + | "wb" |
| + + + | "ab" |
| + + | "ab" |
| + + + | "wb" |
| + + | "rb" |
| + + + | "r+b" |
| + + + + | "w+b" |
| + + + + | "a+b" |
| + + + | "a+b" |
+-----------------------------------+-------------------+
正如您所看到的,您的标志组合是,而不是该表中的。
[C++11: 27.9.1.4/2]:
[..]如果mode
不是表中显示的某些标志组合,则打开失败。
这些就是语义。
&匕首[C++11: 27.9.1.7/2]
&[C++11: 27.9.1.11/2]
向我们展示了模式是从流对象传递到缓冲区对象的
- app(=append(:在每次输出操作之前,将流的位置指示器设置到流的末尾
- trunca(=truncate(任何当前内容都将被丢弃,假设打开时长度为零
正如你所看到的,把两者放在一起是没有意义的。
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 使用ios:ate写入到流会覆盖现有文件
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 朱奇断言失败 - iirfilter iOS
- 不同的std::random_shuffle算法导致iOS模拟器单元测试失败
- 与iOS项目上的C 库链接失败
- iOS 和 OpenCV 错误:断言在 PhaseCorrelateRes 中失败
- pthread_join()在ios上失败
- 为什么ofstream( "log.txt" , ios::app|ios::trunc);总是失败?
- 编译iOS版OpenCV失败-Cmake失败
- iOS:从c++代码构建静态库失败