gpt4 book ai didi

c - 将 perror 与参数一起使用

转载 作者:行者123 更新时间:2023-12-02 18:55:34 24 4
gpt4 key购买 nike

将参数传递给 perror() 是否很常见,或者它通常用于非常通用的消息。例如,类似:

char buffer[50];
sprintf(buffer, "The file %s could not be opened", filename);
perror(buffer);

我问的原因是因为 perror 的单个参数似乎必须是字符串文字(没有任何格式说明符),因此也许它不鼓励使用任何变量?

或者,是否有一种简短的方法可以执行以下操作:

perror("The file %s could not be opened", filename);

(也许是一个宏?)

最佳答案

perror 声明为:

void perror(const char *s);

来自手册页:

First (if s is not NULL and *s is not a null byte ('\0')), the argument string s is printed, followed by a colon and a blank. Then an error message corresponding to the current value of errno and a new-line.

由此,我们可以假设 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的结果>

关于c - 将 perror 与参数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66202939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com