PDA

View Full Version : How to set QFile file name with path with windows separators "\"?



freely
8th August 2011, 19:52
Hello,
When I try to create new file in directory ( that has such permissions ) on Linux it works ok but on Windows I get the errors ( file.errorString() = "The parameter is incorrect" ) , file.error = 5 ):


QFile file(outputDir_+"/"+fileName);
if (!file.open(QFile::WriteOnly))
{
QMessageBox::warning(0,"Could not create Project File",
QObject::tr( "\n Could not create Project File on disk"));

return false;
}

In Qt docs it is written that Qt 4.> automatically translates file name with path to such that contains separators for underlying system ( Linux - "/" , Windows - "\" ) and it is enought to pass to QFile constructor path with "/" separators , but when I call file.fileName() on Windows I get the "/" separators, another worlds how to create new file on windows?
Can anybody help/point what is the problem? Can anybody provide code snippet to create QFile on Windows? What to pass to QFile constructor as file name?
Thanks in advance.

Talei
8th August 2011, 21:33
Your code should work, i.e. (modification from Your previous post, tested on winXP SP3):


QString outputDir = QDir::currentPath(); // with "/" separators
QString fileName = QString( "%1%2" ).arg("some_file_name").arg( ".dat" );
QString fileOut = outputDir+ "/" +fileName;

QFile file( fileOut );
if (!file.open( QIODevice::WriteOnly )) {
qDebug() << "Could not create Project File";
}else{
qDebug() << "Opened: " << fileOut;
}
outputs:
Opened: "C:/Qt/.../some_file_name.dat"
Windows can handle slash (c:/path/to/file.txt) and backslash (c:\path\to\file.txt) (try it in explorer).

You can even do something crazy like this:

QString fileOut = outputDir+ "\\" +fileName;
outputs:
Opened: "C:/Qt/...\some_file_name.dat"

If you use QtCreator do Build->Clean All / Clean Project (maybe some moc file are interfering), check if file is not used by any other app (if You work with existing files), check Your permission (and app) to the directory that You write file into.

wysota
9th August 2011, 08:09
Modern Windows can work with slash separators too so that shouldn't be a problem. If you want to be supercareful then pass QDir::separator() instead of "/".

freely
9th August 2011, 09:37
Separators are “treated” automatically by Qt. I’ve changed file name for Windows and now it works.
Thanks for your help. Solved.