PDA

View Full Version : How to prevent saving when files are opened by another process



jshafferman
15th September 2011, 22:20
I currently have an application that opens several .csv files and stores them in temporary holders (QHash, QList...). The problem I have seen is that when the user clicks the 'Save' option I try and open the files and save all the information contained in the temporary objects to the corresponding .csv files. If the user has one of those files open in say Microsoft excel how do I control the way that event is handled? Is there a special function in QFile or QTextStream that I can call to check this status? Right now very strange behavior happens because one file might get saved while the others aren't so the files are no longer in sync and the application just crashes which is obviously not a desired behavior.

amleto
15th September 2011, 23:58
Is your problem multiple different files not saving at the same time? Or is it multiple 'handles' on a single file becoming out of sync?

jshafferman
16th September 2011, 03:10
Multiple files not saving at the same time, currently these file names are kept in a QList<QString> and then read in one at a time when attempting to save. Thus if one file is open in e.g. Excel then the saving process gets thrown out of whack. I realize that this could be an improper way of saving multiple files and if so please feel free to suggest a different route based on correctness, however I still would like to know if it is possible to do what I initially asked. Thanks again for any help!

ChrisW67
16th September 2011, 06:50
I am assuming the problem arises because Excel locks one or more of the files.

Attempt to open open all three files for QIODevice::ReadWrite and check that they opened successfully before truncating and writing anything. The files that can be opened should not be truncated by this, and the files that cannot be opened should cause you to not write anything.



QFile a("a.txt");
QFile b("b.txt");
QFile c("c.txt");

if (a.open(QFile::ReadWrite) && b.open(QFile::ReadWrite) && c.open(QFile::ReadWrite)) {
qDebug() << "All opened";
a.resize(0);
QTextStream as(&a);
as << QDateTime::currentDateTime().toString() << endl;

QTextStream bs(&b);
b.resize(0);
bs << QDateTime::currentDateTime().toString() << endl;

QTextStream cs(&c);
c.resize(0);
cs << QDateTime::currentDateTime().toString() << endl;
}
else
qDebug() << "Not opened";
a.close();
b.close();
c.close();