如何在C++中使用errno

问题描述 投票:0回答:3

我不明白c++中的errno库是做什么用的?其中设置了哪些类型的错误以及我如何知道哪个数字代表哪个错误?

影响程序执行吗?

c++ error-handling
3个回答
20
投票

errno.h 是 C++ 的 C 子集的一部分。它由 C 库使用并包含错误代码。如果对函数的调用失败,则变量“errno”将相应地设置为错误。

如果你使用的是C++标准库,那就没有用了。

在 C 中,有将 errno 代码转换为 C 字符串的函数。如果您的代码是单线程的,则可以使用 strerror,否则使用 strerror_r (请参阅 http://www.club.cc.cmu.edu/~cmccabe/blog_strerror.html

例如在 C 中,它的工作原理如下:

 int result = call_To_C_Library_Function_That_Fails();

 if( result != 0 )
 {
    char buffer[ 256 ];
    strerror_r( errno, buffer, 256 ); // get string message from errno, XSI-compliant version
    printf("Error %s", buffer);
     // or
    char * errorMsg = strerror_r( errno, buffer, 256 ); // GNU-specific version, Linux default
    printf("Error %s", errorMsg); //return value has to be used since buffer might not be modified
    // ...
 }

当您使用 C 库或 C 语言的操作系统库时,您当然可能在 C++ 中需要它。例如,如果您在 Unix 系统中使用 sys/socket.h API。

使用 C++,如果您要围绕 C API 调用进行包装,则可以使用自己的 C++ 异常,该异常将使用 errno.h 从 C API 调用错误代码中获取相应的消息。


0
投票

无意冒犯最高票答案的作者,但我觉得它具有误导性且不准确。 errno.h 并不完全是“C 的一部分”,它是由 Posix 定义的(https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/),并且您的 C++ 标准库实现很可能依赖于您系统上的 Posix api(是的,在 C 中定义的)。事实上,如果您在这里查看有关标准库的文档,包括 cerrno (https://en.cppreference.com/w/cpp/error/errno),您会看到:

一些标准库函数通过向 errno 写入正整数来指示错误。

因此,要回答您的“它是做什么用”的问题, errno 基本上看起来像一个“全局变量”,并且按照您的目的工作,您绝对需要它来找出 posix 调用失败的原因,因为模式通常是调用返回 <0 and you get the error code by dereferencing errno.

#include <iostream>
#include <fstream>
#include <cerrno>

int main(int argc, char* argv[]) 
{
    std::ifstream f("/file_that_does_not_exist.txt");
    if (!f) {
        std::cout << "file open failed: " << errno << "\n";
    }
    return 0;
}

-1
投票

这就是在现代 c/c++ 中打印 errno 的方式

#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *f = fopen("./scressenshot.png", "r");
    if(f == NULL) {
        printf("fopen failed(): %s\n", strerror(errno))
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.