fopen和fclose? [英] fopen and fclose?

查看:96
本文介绍了fopen和fclose?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果fopen失败,是否需要调用fclose?


我看到这样的例子:

....

stream = fopen(...);

if(stream == NULL)

{

....

}

其他

{

....

}

fclose(stream);

....


根据我的理解,它应该是这样的:

....

stream = fopen(...);

if(stream == NULL)

{

....

}

其他

{

....

fclose(stream);

}

if fopen failed, does it necessary to call fclose?

I see an example like this:
....
stream = fopen(...);
if(stream == NULL)
{
....
}
else
{
....
}
fclose(stream);
....

By my understanding, it should like this:
....
stream = fopen(...);
if(stream == NULL)
{
....
}
else
{
....
fclose(stream);
}

推荐答案

它应该是这样的:


stream = fopen(...);

if(stream == NULL)

{

...

}

其他

{

...

fclose(stream);

}


fclose''ing NULL指针未定义,可能会导致问题。

fclose只有它是一个流一个有效的开放流。

It should be like this:

stream = fopen(...);
if (stream == NULL)
{
...
}
else
{
...
fclose(stream);
}

fclose''ing a NULL pointer is undefined and could cause problems.
fclose a stream ONLY iff it is a valid open stream.


kathy写道:
如果fopen失败,是否有必要调用fclose?


使用空指针调用fclose并不会造成任何损害,如果无法关闭提供的话,

函数将返回错误代码

档。

我看到一个这样的例子:
...
stream = fopen(...);
if (stream == NULL)
{
...
}

{
...
}
fclose (流);
...

根据我的理解,它应该是这样的:
...
stream = fopen(...);
if(stream == NULL)
{
...
}

{
...
fclose(流);
}
if fopen failed, does it necessary to call fclose?
It doesn''t hurt anything to call fclose with a null pointer, and the
function will return an error code if it fails to close the supplied
file.

I see an example like this:
...
stream = fopen(...);
if(stream == NULL)
{
...
}
else
{
...
}
fclose(stream);
...

By my understanding, it should like this:
...
stream = fopen(...);
if(stream == NULL)
{
...
}
else
{
...
fclose(stream);
}




你的方式更可取,恕我直言,但我认为要么是合法的。更好的是

可能会改为使用std :: fstream。 :-)


干杯! --M



Your way is preferable, IMHO, but I think either is legal. Better still
might be to use std::fstream instead. :-)

Cheers! --M


kathy写道:
如果fopen失败,是否有必要调用fclose?


编号实际上我找不到任何关于将要发生什么的描述

如果你将空指针传递给''fclose ''。结论:它未定义

行为,应该避免。 IOW,你必须_not_调用''fclose''来获取从''fopen'获得的
a指针,如果打开失败(并且空指针是

返回)。

[..]
if fopen failed, does it necessary to call fclose?
No. And actually I can''t find any description of what''s going to happen
if you pass a null pointer to ''fclose''. Conclusion: it''s undefined
behaviour and should be avoided. IOW, you must _not_ call ''fclose'' for
a pointer obtained from ''fopen'' if opening failed (and null pointer is
returned).
[..]




V



V


这篇关于fopen和fclose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆