读书人

fstream文件输入输出的有关问题

发布时间: 2012-03-15 11:50:39 作者: rapoo

fstream文件输入输出的问题
下面程序建立不了文件,不知道哪里出错了?

只想定义一个fstream类型来完成输入输出的工作.

#include <iostream>
#include <conio.h>
#include <fstream>

using namespace std;

int main()
{
fstream file( "a.txt ",fstream::in|fstream::out|fstream::app);
string s1,s2;

if(!file) cerr < < "error " < <endl; //执行了这一句,不知道为什么?

s1= "abcd 1234\n ";
file < <s1; //写不进a.txt中
file.flush();
file.seekg(0);
file> > s2;
cout < < "s2= " < <s2 < <endl;//s2为空

file.close();

getch();
return 0;}

dev-c++环境下,没有出现编译错误

程序可以运行,结果是:

error

s2=

程序执行了error这一句,说名文件a.txt没有建立起来,但是我不知道为什么文件没有建立起来?

[解决办法]
因为fstream::in|fstream::out|fstream::app是非法组合。
要么in|out(C的r+)、in|out|trunc(C的w+),要么out|app(C的a)

读书人网 >C++

热点推荐