向perror()传递参数是常见的,还是通常用于非常通用的消息。例如,类似于:
char buffer[50];
sprintf(buffer, "The file %s could not be opened", filename);
perror(buffer);我之所以问这个问题,是因为似乎perror的单个arg必须是字符串文本(没有任何格式说明符),所以它可能不鼓励使用任何变量?
或者,有没有一种简捷的方式来做这样的事情:
perror("The file %s could not be opened", filename);(可能是宏?)
发布于 2021-02-15 05:44:21
perror声明为:
void perror(const char *s);从手册页:
首先(如果s不是NULL,*s不是空字节('\0')),参数字符串s被打印出来,后面跟着冒号和空白。然后是对应于errno当前值和一个新行的错误消息.
这样,我们就可以假设perror基本上被定义为:
fprintf(stderr, "%s: %s\n", s, strerror(errno));作为一个宏,它可以实现为:
#define MY_PERROR(FMT,...) \
fprintf(stderr, FMT ": %s\n", ##__VA_ARGS__, strerror(errno))根据您的示例,使用如下:
MY_PERROR("The file %s could not be opened", filename);输出结果如下:
无法打开文件:< strerror>的结果
发布于 2021-02-16 19:36:49
您可以使用:
#include <string.h> /* for strerror() */
#include <errno.h> /* for errno */
#include <stdlib.h> /* for EXIT_FAILURE */
#include <fcntl.h> /* open and O_RDONLY */
...
if ((fd = open(file, O_RDONLY)) < 0) {
fprintf(stderr, "open: %s: %s (errno = %d)\n",
filename,
strerror(errno),
errno);
exit(EXIT_FAILURE);
}而且你不需要使用任何你喜欢的参数。
https://stackoverflow.com/questions/66202939
复制相似问题