在Qt、c++中获取最后的错误编号

Get the last error number in Qt, C++

本文关键字:最后的 错误 编号 获取 Qt c++      更新时间:2023-10-16

我正在测试一个应该创建并写入文件的函数,该文件的名称作为函数的参数给出。函数失败时返回false。是否有任何方法可以在windows上获得像GetLastError()这样的错误编号??

对于QFile类的方法,您可以使用返回FileError enum的方法error

如果您对获取文件操作的"最后"错误感兴趣,您可以执行以下操作:

bool makeSomethingWithFile(const QString &fileName, QString *error)
{
    QFile file(fileName);
    // Perform something with the file
    // ...
    // On error
    if (file.error() != QFile::NoError) {
        *error = file.errorString();
        return false;
    }
    return true;
}

当你调用这个函数时,只需提供错误字符串:

QString error;
if (!makeSomethingWithFile("myfile", &error)) {
    qDebug() << "The error occurred:" << error;
}

好吧,如果你需要错误作为一个数字,使用FileError enum而不是字符串。