【问题标题】:Error handling with QFile while writing data写入数据时使用 QFile 处理错误
【发布时间】:2018-02-06 08:06:08
【问题描述】:

我想用QFile 打开一个文件,写入它,并正确检查所有可能的错误。我有found 如何使用std::ofstream:

std::ofstream f(...);
//  all sorts of output (usually to the `std::ostream&` in a
//  function).
f.close();
if ( ! f ) {
    //  Error handling.  Most important, do _not_ return 0 from
    //  main, but EXIT_FAILUREl.
}

如果我将operator<<() 与QFile 一起使用,是否可以以类似的方式进行错误检查?

我发现是使用write方法并将返回值与要写入的字符串长度进行比较。

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    如果您想使用operator<< 进行写入,则需要QDataStream 或QtextStream 之类的流。每次写入后,您可以检查流状态:

    QFile file("out.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;
    
    QTextStream out(&file);
    out << "The magic number is: " << 42 << "\n";
    if (out.status() != QTextStream::Ok)
    {
       // FAILED
    }
    

    【讨论】:

    • 不可能因为缓冲而没有实际写入,以后实际写入时可能会出现错误?
    • 我认为可以,但这很困难,因为有多个级别的缓冲和特定于平台的(请参阅 QIODevice::Unbuffered)。您可以尝试刷新和同步。或者甚至是交易。
    • @A.A,对于这个问题,最好写 ...&lt;&lt; endl 而不是 ...&lt;&lt;"\n",因为它会立即刷新流和设备。
    • @MohammadKanan。我更喜欢显式调用flush,因为endl 使整个i/o 变得不必要的慢,除非你真的需要它。但它对 Linux 上的内核缓冲区没有帮助。
    • @A.A,我不知道为什么会遇到 slow 缓慢,但在 Qt 中,&amp;endl 相当于 stream &lt;&lt; '\n' &lt;&lt; flush;。 . 而不是单独做每个
    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 2012-03-25
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多