QTemporaryFile是空的

Int*_*ide 3 c++ qt temporary-files

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

我试试这段代码:

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

qDebug() << file.readAll();
Run Code Online (Sandbox Code Playgroud)

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

""
Run Code Online (Sandbox Code Playgroud)

我怎么能写一个字符串QTemporaryFile?

Sin*_*all 7

一切都很好.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
Run Code Online (Sandbox Code Playgroud)