Frage

I am new to Qt, and I was learning on its Getting Started Page. I want to know what does the following statements mean and why are they required?

In Open function:

if (!file.open(QIODevice::ReadOnly)) {

    QMessageBox::critical(this, tr("Error"), tr("Could not open file"));

    return;
}

Also in Save function:

if (!file.open(QIODevice::WriteOnly)) {
            // error message
} 

I was unable to run these functions without these lines. I tried reading about Error Handling in the documentation but couldn't exactly find what do these statements mean.

War es hilfreich?

Lösung

You can open files for reading and for writing. Using QIODevice::WriteOnly or QIODevice::ReadOnly flags you are specifying mode in which you will open particular file.

But, why does it matter?

Suppose you have one file opened in several instances of different programs, and that there is no such thing as specifying file mode. Now, if every files are reading file - since they all have different pointer to the current position in the file - this is not a problem - since all programs will get the latest and correct information from file. But, if only one programs write something into file - your data will be inconsistent, so other programs will potentially read wrong data.

Intuitive approach would be to send a message to all programs that are attached on this file, so they could update themselves. But - what to do if the file is deleted? Or if there is no possibility to set the proper position in the new data? Also, every program now needs to have interface in order to be notified, and the whole message passing idea can be very slow (aside that it doesn't work).

So - there is simply consensus made - multiple programs can open file for reading - as they will all have the same and consistent data. But, if the only one program is signaling the operating system that it wants to gain write permissions - the file must not be opened in any program - nor for reading - nor for writing! Depending on the implementation, operating system may block the caller until all files are closed, or it can simply ignore the call and send the error information to caller - which is often a better idea, as the program (or the user) can block itself and try again later, or it can simply ask user to save into another destination, or it can send us creepy error message - but it will not be able to write into file.

Last paragraph is describing what is known as multiple readers-single writer technique, so you may want to look it up on the internet or concurrency classes textbooks.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top