c++ - 摆脱编译器警告 "warning: result of call is not used"

标签 c++ c

我正在处理一些包含以下功能的遗留代码。总之,该函数从文本文件中读取一行,去除前导/尾随空格和换行符,检查错误,并在成功时返回字符串中的字符数或在错误时返回 -1。你能给我一些提示来摆脱警告吗?我知道这不是错误,但我想改进代码。谢谢!

static int readline(file *mf, char *buf, int n, int strip) {
    if (!buf || n < 1 || !mf) return seterror(MDIO_BADPARAMS);

    // Read the line
    fgets(buf, n, mf->f);

    // End of file reached?
    if (feof(mf->f)) return seterror(MDIO_EOF);

    // File I/O error?
    if (ferror(mf->f)) return seterror(MDIO_IOERROR);

        // comment line?
        if (buf[0] == '#') return readline(mf,buf,n,strip);

    // Strip whitespace
    if (strip) strip_white(buf);

    return strlen(buf);
}

该函数能够编译 (nvcc) 但它有警告:

warning: result of call is not used

最佳答案

fgets 使用 warn_unused_result 属性声明。不检查结果通常是一个编程错误:如果 fgets 未能读取任何内容,它会返回 NULL 并保持缓冲区不变。如果您不检查这种情况,您可能会处理陈旧或未初始化的数据。

要解决这个问题,只需检查结果:

if(!fgets(buf, n, mf->f)) return seterror(MDIO_EOF);

关于c++ - 摆脱编译器警告 "warning: result of call is not used",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193117/

相关文章:

c++ - 如何 dynamic_cast 一个没有虚方法的类的指针?

c++ - 在 Eclipse CDT 中折叠 C++ 类的私有(private)部分?

c++ - 为什么 main 没有定义 `main(std::vector<std::string> args)` ?

c++ - stringstream 不会转换为正确的数值

c++ - 如何在 C++ 中正确定义模板的流运算符

编译器错误 C2432 : illegal reference to 16-bit data in 'identifier'

c++ - 当在其中定义全局变量时,如何在 .cpp 中包含 C 风格的 .h?

c - 如何从C中的.txt文件读取和打印前5个整数?

c - 用更大数组的字符填充 char 数组 | @ assembly IA32

c - 外部功能不起作用 - 但不确定原因