简体   繁体   English

错误:perror 和 fprintf 之间的区别

[英]Error: difference between perror and fprintf

Any difference between the following two approaches when encountering and error?遇到错误时以下两种方法有什么区别?

if (!mallocd_buffer) {

    // this?
    fprintf(stderr,"malloc() failed in file %s at line # %d", __FILE__, __LINE__);

    // or this?
    perror("Failed to copy a string\n\n\n\n\n");

    exit(EXIT_FAILURE);
}

Using perror , you get the system error message implied by the current value of errno in the output, after the string you supply as the argument.使用perror ,您会在作为参数提供的字符串之后获得 output 中errno的当前值所暗示的系统错误消息。

Using fprintf(stderr, "…", …) , you're in complete control of the formatting.使用fprintf(stderr, "…", …) ,您可以完全控制格式。

I rarely use perror() ;我很少使用perror() it doesn't meet my requirements as formatting the string to pass to it is fiddly.它不符合我的要求,因为格式化要传递给它的字符串很繁琐。 I use the functions I wrote such as err_syserr() — code which is available in my SOQ (Stack Overflow Questions) repository on GitHub as files stderr.c and stderr.h in the src/libsoq sub-directory.我使用我编写的函数,例如err_syserr() — 代码在我的 GitHub 上的SOQ (堆栈溢出问题)存储库中作为文件stderr.cstderr.hsrc/libsoq子目录中可用。

On BSD, there is a similar package called err(3) ;在 BSD 上,有一个类似的 package 称为err(3) you can find it on Linux too (see err(3) ).你也可以在 Linux 上找到它(参见err(3) )。 You will probably prefer to use that over my code, if only because the system functions manage to be privy to the value of argv[0] indirectly, whereas my code isn't because there isn't a portable interface to gain access to argv[0] except via the arguments to main() ) and my code therefore relies on you calling err_setarg0(argv[0]) in main() to set the program name.您可能会更喜欢在我的代码上使用它,如果只是因为系统函数设法间接了解argv[0]的值,而我的代码不是因为没有可移植的接口来访问argv[0]除了通过 arguments 到main()之外,因此我的代码依赖于您在main()中调用err_setarg0(argv[0])来设置程序名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM