fopen 返回 NULL,但 perror 打印成功?
是的,我有这个代码:
if(argc>1){
FILE * pFile = fopen(argv[1],"rb");
perror("");
}else{
FILE * pFile = fopen("hardcoded","rb");
}
if(pFile==NULL){
puts("Unable to open source file");
return -1;
}
但是,我得到了这个奇怪的输出:
Success
Unable to open source file
更奇怪的是,如果我这样做:
if(argc>1){
FILE * pFile = fopen(argv[1],"rb");
perror("");
}else{
FILE * pFile = fopen("hardcoded","rb");
}
FILE * pFile = fopen("hardcoded","rb");
if(pFile==NULL){
puts("Unable to open source file");
return -1;
}
在硬编码存在的地方,一切都工作正常!
那些火苗是什么意思?
在 Ubuntu 上使用 GCC4 进行编译
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我对你的代码编译感到惊讶,因为你声明
FILE *pFile
范围为 if 和 else 块。如果您在此之前已声明它,请删除 if/else 块中赋值前面的FILE*
文本。I'm surprised your code compiles, since the you are declaring
FILE *pFile
scoped to the if and the else blocks. If you've declare it prior to that, then remove theFILE*
text in front of the assignments in the if/else blocks.不要在
if
语句中定义 pFile,否则您将失去范围。Don't define pFile within the
if
statement, you're losing scope.我敢打赌,您之前的代码中已经有一个
FILE * pfile;
您没有包含在内。如果它位于所有块之外,并且具有静态存储持续时间,则将其初始化为 NULL。当您在内部块中有 FILE * pfile = fopen(... 时,这两个 pfile 是两个不同的东西。因此,发生了什么:
您正在定义
pfile
在一个块中,然后很好地打开它,然后到达块的末尾,它就像块中的任何其他本地变量一样被丢弃,您只剩下原始的
pfile 。
,您从未打开或分配任何内容到,这很可能是 NULL。在第二种情况下,您打开一个文件并丢弃它,然后您将在与测试
if 相同的范围内得到一个
语句,这就是您正在测试的语句,因此FILE * pfile
。您只需定义一次
pfile
就可以了,因为额外的定义要么会导致编译器错误,要么会给您提供单独的版本。获取所有文件*
超出您的内部块,并且始终使用相同的pfile
。I'd bet you've got a
FILE * pfile;
earlier in your code that you didn't include. If it's outside all blocks, and has static storage duration, it's initialized to NULL.When you then have
FILE * pfile = fopen(...
in an inner block, the twopfile
s are two different things. Therefore, what's happening:You're defining
pfile
in a block, and opening it fine. Then you reach the end of the block, and it's being discarded like any other variable local in a block.You're left with the original
pfile
, which you never opened or assigned anything to, and that's likely to be NULL.In the second case, you're opening a file and discarding it, and then you have a
FILE * pfile
in the same scope as the testingif
statement, and that's the one you're testing, so it's fine.What you need to do is define
pfile
only once, since additional definitions will either cause compiler errors or give you separate versions. Take all theFILE *
out of your inner blocks, and just use the samepfile
all the time.