Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty file in Qt

Tags:

c++

qt

qt4

I have a file named DBFile. I am using the following code:

QString DBfile ="C:/Users/E543925/Desktop/VikuTB.xml";
QFile newFile(DBfile);
newFile.open( QIODevice::WriteOnly);

Now I want to write something inside the file if it is empty. How can I check whether a file is empty or not in Qt?

like image 367
Learner Avatar asked Dec 26 '22 18:12

Learner


2 Answers

add the append flag and check the insertion pointer:

newFile.open( QIODevice::WriteOnly|QIODevice::Append );
if (newFile.pos() == 0) {
  // is empty
} else {
  // some data inside
}

disclaimer: untested code, now i'll take the time to try it...

edit: tested, seems to work well...

like image 24
CapelliC Avatar answered Jan 08 '23 23:01

CapelliC


Check file size before open by newFile.size()

like image 79
Vlad Gordin Avatar answered Jan 09 '23 00:01

Vlad Gordin