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