2015-09-18 27 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