【问题标题】:Why opening a file in c++ with input,output,append mode gives error?为什么在 C++ 中使用输入、输出、追加模式打开文件会出错?
【发布时间】:2023-06-23 02:00:01
【问题描述】:
#include <iostream>
#include <fstream>

int main()
{
    using namespace std;

    /* Open a file and read it*/

    ofstream file_obj;

    file_obj.open("file1.txt",ios::in| ios::out | ios::app);

    if( file_obj.is_open() )
    {
       printf("\n File opened successfully ");
    }
    else
    {
       printf("\n Error occured in opening the file");
    }

    return 0;
 }

它给出输出

打开文件时出错。

但是当我删除 ios:in 它工作正常。

为什么这种组合是不可能的?

【问题讨论】:

  • 不,这不是一个有效的组合(即使是fstream)。可以打开一个文件以读取 XOR 以进行追加,而不是两者兼而有之。只需为inout 打开fstream(因为ofstream 仅用于输出)并移至文件末尾。
  • @Cyber​​ 但对我来说 ios:in 和 ios:out 工作正常。
  • 失败的原因是什么? (提示:尝试检查errno。)您的代码适用于我,适用于 VC++ 和 g++(尽管有其他人的 cmets,但它是完全合法的)。
  • @Adriano 似乎 ofstream 允许 ios:in 和 ios:out 。这怎么可能
  • @VinothKumar 为什么不可能呢?打开只是传递给std::filebuf,它没有输入和输出版本。 (当然,实际读取文件的唯一方法是获取filebuf。)

标签: c++ file ofstream


【解决方案1】:

ofstream 类仅用于输出(写入文件) - 因此是“o”。请改用fstream - 这允许输入和输出。

【讨论】:

  • ios::inios::app 即使对于 fstream 也不是有效的组合(在 C++ 98 中,在 C++ 11 中是允许的)。
  • @Adriano 嗯,我尝试编译他的代码,它工作正常。也许他把 file1.txt 放在 Debug 文件夹而不是他的项目文件夹中。
  • @willywonka_dailyblah 他的代码没有问题。但在他发布实际错误之前,我们不能说太多。
最近更新 更多