perror 生成意外的 errno 值
在将 perror
与 glibc
结合使用时,我遇到了意外的 errno
值。当将不存在的文件指定为 arg[1]
时,它会按预期打印 Error: 2
(即 ENOENT
)。然而,当下面的 perror
行被取消注释时,无论我传递什么,它都会抛出错误 22 (EINVAL
)。谁能解释一下为什么要这样设置吗?
编辑:看起来这是某种 Eclipse 错误。 IDE 似乎导致 perror 抛出某种错误,该程序在命令行上完美运行,并且当在 Eclipse 中的参数列表中指定正确的文件时也完美运行。在 Eclipse 中运行时会错误地失败。
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *input_file;
input_file = fopen(argv[argc - 1], "r");
if (!input_file) {
// perror(argv[argc-1]);
fprintf(stderr, "Error: %d\n", errno);
return (EXIT_FAILURE);
}
else {
fclose(input_file);
}
return (EXIT_SUCCESS);
}
I am experiencing an unexpected value of errno
when using perror
with glibc
. When an non-existent file is specified as arg[1]
it prints Error: 2
( which isENOENT
) as expected. However when the perror
line below is uncommented it throws error 22 (EINVAL
) no matter what I pass it. Can anyone please explain why this is getting set?
EDIT: Looks like this is some sort of Eclipse bug. The IDE seems to be causing perror to throw some sort of error, the program works perfectly on the command line, and works perfectly when a correct file is specified in the argument list in Eclipse. It fails incorrectly when run inside of Eclipse.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *input_file;
input_file = fopen(argv[argc - 1], "r");
if (!input_file) {
// perror(argv[argc-1]);
fprintf(stderr, "Error: %d\n", errno);
return (EXIT_FAILURE);
}
else {
fclose(input_file);
}
return (EXIT_SUCCESS);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用其他库函数后,您不能依赖 errno 的值,换句话说,您对 perror() 的调用本身可能会修改 errno 的值,您需要如果您希望在调用其他库过程后能够使用它,请将其保存在临时变量中。
You can't rely on the value of
errno
after calling into other library functions, in other words your call to perror() itself may be modifying the value oferrno
You need to save it in a temporary variable if you want to be able to use it after calls into other library procedures.您的程序在这里按我的预期工作:
并且
perror()
调用未注释:也许
perror()
调用正在更改您的errno
有什么原因吗?您使用什么操作系统/编译器/库版本?Your program works as expected for me here:
and with the
perror()
call uncommented:Maybe the
perror()
call is changing yourerrno
for some reason? What operating system/compiler/library versions are you using?他很可能在没有任何参数的情况下运行该程序。
如果是这样,“argv[argc - 1]”将评估为垃圾。
应该有代码来确保“argc-1”在有效范围内。
He's likely running the program without any arguments.
If so, "argv[argc - 1]" will evaluate to garbage.
There should be code to make sure that "argc-1" is within a valid range.