Solved Can't read from file when QIODevice::Append is specified
-
as the title suggests, i can't read fro ma file when i open it in
file.open(QIODevice::ReadWrite | QIODevice::Append);
mode.
removing qiodevice::append makes it work. what can i do?
-
Hi,
Can you show the code you are using ?
-
QFile file(path/to/file); file.open(QIODevice::ReadWrite | QIODevice::Append); if(!file.isOpen()) { QMessageBox::information(nullptr, "Error", file.errorString()); return false; } while(!file.atEnd()) fileContents.insert(file.readLine()); }
the file gets opened, however, the while loop never executes (the file does contain content)
-
@user4592357
Do you need to seek to the start after opening? Like append is placing the pointer at the end? -
@user4592357 said in can't read from file when qiodevice::append is specified:
as the title suggests, i can't read fro ma file when i open it in
file.open(QIODevice::ReadWrite | QIODevice::Append);
mode.
removing qiodevice::append makes it work. what can i do?
And BTW you don't have to specify append in order to write at the end, you can always seek there.
-
@user4592357
I scribbled above responses in haste last night. Briefly to clarify:- When you do I/O from/to a file there is one "file pointer" for "the current position".
- If you both read & write, they share the same file pointer position.
- If you specify "append" when opening, it is common for the file pointer to be immediately positioned at the end of the file, rather than the beginning which is where it is if "append" is not requested.
- Hence with "append" your
file.atEnd()
is immediately true, so your loop is not entered. - You can move the "file pointer" via
QIODevice::seek()
. For exampleQIODevice::seek(0)
immediately after opening in your case. - "append" mode on opening will cause the file pointer to be automatically positioned for you at the end immediately prior to any attempt to write to the file, ensuring you can never overwrite content.
- You can also achieve same without using "append" mode if you wish to by explicitly seeking to end prior to performing any write.
- Other implementations of "seeking" I have seen have a symbolic way of saying "seek to end". I don't see that for
QIODevice::seek(qint64 pos)
, so you may have to useQIODevice::seek(QIODevice::size())
, or similar. - Word of warning: don't be tempted to use
QIODevice::seek(9999999999)
or similar as a shortcut, it will (probably) extend your file size to become 9999999999 ... ! - Finally, if not using append mode for opening, it is common for there to be a restriction which requires you to do a seek whenever you change from reading to writing or vice versa to correctly deal with the file pointer position.
:)