如果调用了fclose(0),这会关闭stdin吗? [英] If fclose(0) is called, does this close stdin?
问题描述
如果调用了fclose(0),这会关闭stdin吗?
If fclose(0) is called, does this close stdin?
之所以这样问,是因为某种原因,stdin在我的应用程序中被关闭了,我无法弄清原因.我检查了fclose(stdin),但它不在应用程序中,所以我想知道fclose(0)是否会导致未定义的行为,例如关闭stdin?
The reason why I'm asking this is that for some reason, stdin is being closed in my application and I cannot figure out why. I checked for fclose (stdin) and this is not in the application and so I was wondering if fclose(0) could cause undefined behaviour such as closing stdin?
如果没有,stdin可能被错误关闭的其他方式是什么?
If not, what are other ways that stdin could be erroneously closed?
推荐答案
fclose
的签名是这样:
int fclose ( FILE * stream );
这意味着,fclose
需要一个指向FILE
对象的指针.因此,如果传递0
而不是指针,则将0
理解为NULL
指针 1 .如果它为NULL指针,您如何期望它关闭stdin
?它不会关闭.使用fclose(stdin)
,因为stdin
本身是指向FILE
对象的指针.
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*
),则必须使用<unistd.h>
中的close
.
I think you're confusing stdin
with file-descriptor which is of integral type, and usually denoted as fd
. Its true that fd
of input stream is 0
. So if you want to use fd
(instead of FILE*
), then you've to use close
from <unistd.h>
.
#include <unistd.h>
int close(int fildes);
也就是说,close(0)
将关闭标准输入.
That is, close(0)
would close stdin.
1:似乎很有趣,如果您已通过1
传递给fclose并打算关闭stdout
,则您的代码甚至无法编译,并且您会在编译时立即看到代码问题.现在的问题是,为什么不编译?因为与0
不同,1
不会隐式转换为指针类型.编译器将生成类似"error: invalid conversion from ‘int’ to ‘FILE*’
的消息.请在ideone上查看错误和行号此处.
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.
这篇关于如果调用了fclose(0),这会关闭stdin吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!