如果调用 fclose(0),这会关闭标准输入吗?
我问这个问题的原因是由于某种原因,stdin 在我的应用程序中被关闭,我不明白为什么。我检查了 fclose (stdin),但这不在应用程序中,所以我想知道 fclose(0) 是否会导致未定义的行为,例如关闭 stdin?
如果没有,stdin 可能被错误关闭的其他方式是什么?
的签名fclose
这是:
int fclose ( FILE * stream );
That means, fclose
expects a pointer to FILE
object. So if you pass 0
, instead of a pointer, 0
would be understood as NULL
pointer1. If its NULL pointer, how do you expect it to close stdin
? It will not close. Use fclose(stdin)
, as stdin
itself is a pointer to FILE
object.
我觉得你很困惑stdin
具有整数类型的文件描述符,通常表示为fd
。确实如此fd
输入流的0
。所以如果你想使用fd
(代替FILE*
),那么你必须使用close
from <unistd.h>
.
#include <unistd.h>
int close(int fildes);
那是,close(0)
将关闭标准输入。
1 : It seems interesting that if you had passed 1
to fclose with the intention to close stdout
, your code wouldn't even compile, and you would immediately see the problem with your code at compile-time itself. Now the question is, why would it not compile? Because unlike 0
, 1
is not implicitly converted into pointer type. The compiler would generate message like "error: invalid conversion from ‘int’ to ‘FILE*’
. See the error and line number here at ideone http://www.ideone.com/mz0yx.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)