gpt4 book ai didi

我可以假设 C stdlib 函数不使用 errno 吗?

转载 作者:太空狗 更新时间:2023-10-29 15:11:40 26 4
gpt4 key购买 nike

我正在看一段 C 代码,它是

void printerror(char *message)
{
printf ("There was an error: '%s'\n", message);
switch (errno) {
... do stuff depending on errno
}
}

我认为这可能是个问题,因为 printf 可能会在进入函数和到达 switch 之间更改 errno。但是,printf 的联机帮助页没有说明有关设置 errno 的任何内容,所以我可以假设它永远不会设置它吗?标准中是否有任何内容可以保证哪些函数将使用和不使用 errno?

最佳答案

任何函数都可以设置 errno,但前提是将其设置为非零值。 ANSI C 规范指出:

The value of errno is zero at program startup, but is never set to zero by any library function.* The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in the Standard.

*Thus, a program that uses errno for error checking should set it to zero before a library function call, then inspect it before a subsequent library function call.

因此,如果您使用 errno,最佳实践方法是在可能失败的库调用之前立即将该值设置为 0,并在之后立即读取它。在上述情况下,添加如下内容就足够了:

int localErrno = errno

紧接在 printf 语句之前并使用 localErrno 作为您的开关。当然,这假设在失败的函数和您对 printerror 的调用之间没有库调用。如果有,您需要在调用失败后存储 errno 并将其传递给您的 printerror 函数。

关于我可以假设 C stdlib 函数不使用 errno 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4391026/

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