我想在Qt项目中使用临时文件
我试试这段代码:
QTemporaryFile file;
file.open();
QTextStream stream(&file);
stream << content; // content is a QString
qDebug() << file.readAll();
但是控制台显示一个空字符串:
""
如何在QTemporaryFile
中编写字符串?
答案 0 :(得分:6)
一切都很好。 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