QTemporaryFile 为空

QTemporaryFile is empty

我想在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