【问题标题】:QTemporaryFile is emptyQTemporaryFile 为空
【发布时间】:2015-09-18 09:28:04
【问题描述】:

我想在 Qt 项目中使用临时文件

我试试这个代码:

QTemporaryFile file;
file.open();
QTextStream stream(&file);
stream << content; // content is a QString

qDebug() << file.readAll();

但是控制台显示一个空字符串:

""

如何在QTemporaryFile 中写入字符串?

【问题讨论】:

    标签: c++ qt temporary-files


    【解决方案1】:

    一切正常。 QTemporaryFile 总是以ReadWrite 打开,并且是一个随机访问设备,这意味着在你写入数据之后,你要么需要关闭并重新打开它(这是一个矫枉过正),要么转到开头文件读取:

    QTemporaryFile file;
    file.open();
    QTextStream stream(&file);
    stream << content; // here you write data into file. 
    //Your current position in the file is at it's end, 
    //so there is nothing for you to read.
    stream.flush();//flush the stream into the file
    
    file.seek(0); //go to the begining
    
    qDebug() << file.readAll(); //read stuff
    

    【讨论】:

    • 它不起作用:/我直接查看了文件(位于临时文件夹中),它是空的。
    • @Intelligide,这可能是因为QTextStream 缓存了数据。我已更新答案,添加stream.flush() 以确保数据立即进入文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多