注册 登录
编程论坛 C++教室

帮忙解释一段程序``

tbtbtb520 发布于 2008-01-09 16:44, 1266 次点击
#include <iostream.h>
#include <fstream.h>
using namespaced std;
int main()
{
     ofstream ofs("file.txt");
    if (!ofs)
   {cout<<"打开文件失败"<<endl;   //  这个if语句是什么意思,具体点,还有exit(1)也不明白,里面的参数又是什么。。
    exit(1);
   }

    ofs<<1234<<endl
       <<"tyu"<<endl;
}
9 回复
#2
eagleboycn2008-01-09 17:57
!ofs 应该是fstream输出流对象失败?
exit(1)应该是程序非正常中止?
望高手来解答啊..............

[[italic] 本帖最后由 eagleboycn 于 2008-1-9 18:05 编辑 [/italic]]
#3
tianwangcccc2008-01-09 18:02
asddsf
if(ofs)是如果ofs为真,if(!ofs)是如果非ofs为真
#4
tbtbtb5202008-01-10 10:33
原帖由 [bold][underline]tianwangcccc[/underline][/bold] 于 2008-1-9 18:02 发表 [url=http://bbs.bc-cn.net/redirect.php?goto=findpost&pid=1176148&ptid=196702][/url]
if(ofs)是如果ofs为真,if(!ofs)是如果非ofs为真



这个我当然知道。。。    就是问是什么意思```
2楼的懂我的意思。。不知道是不是对的
#5
忘记喧嚣2008-01-10 13:28
OFS 输出字段分隔符
#6
zhouqingwuji2008-01-10 15:26
我的乖乖!
不回,上白度啊·~·
        世上牛人多如麻,就是不见你这么。。的
#7
kkqq2008-02-19 22:31
打开一个文件~~写入数据~~如果不能打开就退出~~
#8
first_love2008-02-19 23:28
----------------------------------------------
if (!ofs)//表示‘file.txt’文件不存在,即打开失败时就输出以下信息。
{
  cout<<"打开文件失败"<<endl;
  exit(1);//exit(1)参数是C++定义程序不正常时所返回的参数,C++里一般定义返回不正常里用‘1’表示。
}
---------------------------------------------------------------
以上是个人愚见,不对之处还望纠正。
#9
sunkaidong2008-02-20 18:26
explicit basic_ofstream();
explicit basic_ofstream(const char *s,
    ios_base::openmode which = ios_base::out | ios_base::trunc);
The first constructor initializes the base class by calling basic_ostream(sb), where sb is the stored object of class basic_filebuf<E, T>. It also initializes sb by calling basic_filebuf<E, T>().

The second constructor initializes the base class by calling basic_ostream(sb). It also initializes sb by calling basic_filebuf<E, T>(), then sb.open(s, mode | ios_base::out). If the latter function returns a null pointer, the constructor calls setstate(failbit).
#10
天使梦魔2008-02-20 19:09
ofstream ofs("file.txt");
ofstream这里被当成某个变量用,他的变量名是ofs指定打开为txt的文件.
系统检测到这条语句时为寻找文件,如果成功给ofs状态写true
失败写flash
通过判断就可以看出是成功了还是失败了.
(你接触win32开发多了就知道所有的函数和程序都需要有状态值,包括void main也是错误的写法)

exit(1);
16位程序的结束函数,使用它表示这个程序到此终止.
参数1代表错误形态终止,0表示正常形态终止.
你的程序太小,不用考虑状态值
1