gpt4 book ai didi

c++ - 需要在调用函数之前清理 errno 然后检查 errno?

转载 作者:太空狗 更新时间:2023-10-29 23:44:44 28 4
gpt4 key购买 nike

  1. 我们是否需要在调用函数之前将errno 重置为零?请参见下面的代码。现在的场景是 a_dest_path 是一个现有目录。但是当我执行代码时,它总是尝试 mkdir 但返回错误说该目录无法创建,因为它存在。在 GDB 中,我在调用 opendir() 之前检查了 errno 并且 errno 是 2。看起来 errno 不是在调用 opendir() 期间设置为零。那么我是否需要在调用opendir() 之前将errno 重置为零?

  2. errno 可能会在 system() 调用中改变,然后在我的 else if 分支中检查 的结果>system() 但不是 opendir()。所以在 opendir() 之后,我是否需要将 errno 分配给一个变量,然后在 if..elseif..else 分支中检查这个变量?

DIR *dp = opendir(a_dest_path.c_str());
if (errno == ENOENT) {
string mkdir_comman = "mkdir " + a_dest_path;
system(mkdir_command.c_str());
} else if (errno == ENOTDIR) {
printf("Destination %s exists but is not directory\n", a_dest_path.c_str());
return k_error_not_directory;
} else if (errno == 0) {
closedir(dp);
}

最佳答案

不,调用函数之前不需要重置errno,因为the contract reads :

The opendir() and fdopendir() functions return a pointer to the directory stream. On error, NULL is returned, and errno is set appropriately.

测试返回值,只有当你真的有错误时才看errno!

(realloc 是一个罕见的函数示例,在特定情况下,如果不查看 errno 就无法将错误与成功区分开来,但如果是,它将清除它消除歧义所必需的。)

关于c++ - 需要在调用函数之前清理 errno 然后检查 errno?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25315191/

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