有关 fstream 和 ofstream

lewis_c402 2005-04-30 08:48:36

ofstream file;
file.open( "file.out", ios_base::app );
if( !file )
cout << "error";
这样写是对的.

但我把ofstream 改为 fstream 就错了:
ofstream file;
file.open( "file.out", ios_base::app );
if( !file )
cout << "error";

编译后 运行的结果为 error

难到  fstream  不支持ios_base::app
有人知道为什么吗?


...全文
407 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
睡在床板下_ 2005-05-02
  • 打赏
  • 举报
回复
#include <iostream>
#include <fstream>
#include "WordCount.h"

using namespace std;

int main()
{
const int max_size = 1024;
char ch[max_size];
fstream file;

file.open( "file.out", ios_base::in );
if ( !file )
cout << "error";
while( file.getline( ch, max_size ) )
cout << ch;
file.clear();------------------------加上这句
file.close();
file.open( "file.out", ios_base::out | ios_base::app );
if( !file )
cout << "error 2 ";
while( cin.getline( ch, max_size ) )
file << ch;


system( "pause" );
}
lewis_c402 2005-05-02
  • 打赏
  • 举报
回复
#include <iostream>
#include <fstream>
#include "WordCount.h"

using namespace std;

int main()
{
const int max_size = 1024;
char ch[max_size];
fstream file;

file.open( "file.out", ios_base::in );
if ( !file )
cout << "error";
while( file.getline( ch, max_size ) )
cout << ch;
file.close();
file.open( "file.out", ios_base::out | ios_base::app );
if( !file )
cout << "error 2 ";
while( cin.getline( ch, max_size ) )
file << ch;


system( "pause" );
}

那这样怎么回输出 "error 2 ", 呢
flying_dancing 2005-04-30
  • 打赏
  • 举报
回复
同意//////////////
VIAMobile 2005-04-30
  • 打赏
  • 举报
回复
使用fstream时,要指出打开文件是做输入还是做输出用的。使用ofstream的时候,会在打开模式中默认指定ios::out。所以使用ofstream的时候不会有问题。把你的代码改成file.open("file.out", ios::out|ios::app)就可以了.

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧