c++ - 未创建具有 fstream 对象的文件对象

标签 c++ fstream

我正在尝试创建一个二进制文件,如下所示:

#include <iostream>
#include<fstream>

using namespace std;

int main()
{
    cout<<"Hello World";
    fstream fileObj = std::fstream("test_File.db", std::ios::in | std::ios::out | std::ios::binary);
    if(fileObj)
       std::cout<<"success";
    else
       std::cout<<"fail";
    return 0;
}

但是 fileObj 没有被创建,其他部分总是被执行。如果我遗漏了什么,请指导。

最佳答案

A stream opened with in | out | binary does not create a file that does not exist.你应该养成阅读文档的习惯!

在 | 中尝试 出来 |应用 | binary(假设您希望保留现有内容;还要养成明确说明您的目标/要求的习惯)。

而且不需要从这样的临时文件中初始化;只需以通常的方式实例化对象,例如

std::fstream fileObj(
   "test_File.db",
   std::ios::in | std::ios::out | std::ios::app | std::ios::binary
);

关于c++ - 未创建具有 fstream 对象的文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53815414/

相关文章:

c++ - windows.h 的 Beep() 的更快替代品

c++ - 访问模板中的成员: how to check if the template is a pointer or not?

c++ - 非常基本的 C++ 错误

C++ fstream - 仅读取某些变量类型的问题

c++ - 为什么我不能使用 fstream vector ?

c++ - 如何在 C++ 中读取一个空文件?

c++ - 如何在 C++ 中使用一定数量的空格打印输出

c++ - 使用 gcc 链接 Fortran 和 C++ 二进制文件

从 X 长度的文件读取二进制数据时 C++ 程序崩溃

c++ - 我如何使用 goto 来执行文件任务而不是使用函数?