2015-09-18 13 views
2

我想在Qt的项目中使用临时文件QTemporaryFile是空

我试试这个代码:

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

qDebug() << file.readAll(); 

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

"" 

我如何写QTemporaryFile中的字符串?

回答

5

一切工作正常。 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 
+0

这是行不通的:/我直接看文件(位于临时文件夹),它是空的。 – Intelligide

+0

@Intelligide,这可能是因为'QTextStream'缓存了数据。我已经更新了答案,添加'stream.flush()'以确保数据立即进入文件。 – SingerOfTheFall

+0

它适用于'flush'。谢谢 ;) – Intelligide