c++ - QTemporaryFile 为空

标签 c++ qt temporary-files

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

我试试这段代码:

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

qDebug() << file.readAll();

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

""

如何在 QTemporaryFile 中写入字符串?

最佳答案

一切正常。 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

关于c++ - QTemporaryFile 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648536/

相关文章:

c++ - Linux 内存分析工具

c++ - 从我的项目创建一个 EXE 文件

qt - 如何将 LPTSTR 转换为 QString

c# - 如何解锁被 .NET 中的进程锁定的文件

c++ - 将文件嵌入iOS应用(C++/Qt/cmake)

c++ - 将 fstat 与 Qt QDialog 一起使用

linux - 启用 nvidia 卡上的 Qml 应用程序奇怪行为

java - 垃圾收集器销毁对象后删除文件

python - tempfile.TemporaryFile() 在分配给变量后不适用于 sqlite3

C++ if 语句