《发现一个有趣的函数:av_strerror,帮助分析错误码》

这个函数可以帮我们当使用ffmepg里面的API接口时,如果发生错误,得到返回值错误码的同时,还会返回一个错误码相对应的描述。对于我们分析问题十分的方便!!!!
今天第一次知道,十分的激动,原来有如此方便的东西哈哈哈。

去官网查看函数的定义:

int av_strerror(int errnum, char *  errbuf, size_t  errbuf_size)
  1. Parameters参数描述:
  • errnum: error code to describe(错误码值)
  • errbuf: buffer to which description is written(将要被写进错误描述的数组)
  • errbuf_size: the size in bytes of errbuf(数组的字节大小)
  1. Returns返回值:
    0 on success, a negative value if a description for errnum cannot be found
    //返回值为0时,表示成功(可以找到AVERROR CODE整数值的错误描述),如果返回其他值,则说明没有找到错误数值的描述内容。

查看官网上面的函数作用描述:

  • Put a description of the AVERROR code errnum in errbuf.(将错误描述存放再数组errbuf里)
  • In case of failure the global variable errno is set to indicate the error. (在失败的情况下,全局变量 errno 设置为指示错误。)
  • Even in case of failure av_strerror() will print a generic error message indicating the errnum provided to errbuf.(即使在失败的情况下,av_strerror() 也会打印一条通用错误消息,指示提供给 errbuf 的 errnum。)

函数实现:

int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
{
    int ret = 0, i;
    const struct error_entry *entry = NULL;

    for (i = 0; i < FF_ARRAY_ELEMS(error_entries); i++) {
        if (errnum == error_entries[i].num) {
            entry = &error_entries[i];
            break;
        }
    }

    if (entry) {
        av_strlcpy(errbuf, entry->str, errbuf_size);
    } 
    else {
#if HAVE_STRERROR_R
        ret = AVERROR(strerror_r(AVUNERROR(errnum), errbuf, errbuf_size));
#else
        ret = -1;
#endif
        if (ret < 0)
            snprintf(errbuf, errbuf_size, "Error number %d occurred", errnum);
    }
    return ret;
}

函数使用案例:

char buf[] = "";
int err_code = avformat_open_input(&pFormatCtx,filepath,NULL,NULL);//打开输入视频文件
av_strerror(err_code, buf, 1024);

printf("Couldn't open file %s: %d(%s)\n",filepath, err_code, buf);
打印内容

Couldn't open file xxx.mp4: -2(No file or directory)

posted @ 2022-09-14 15:19  程序员没有头发  阅读(458)  评论(0编辑  收藏  举报