5

I'm trying to check if provided path exists and if it is a file.
So I wrote this piece of code:

#include <QFile>
#include <QFileInfo>


bool Tool::checkPath(const QString &path){
    QFileInfo fileInfo(QFile(path));
    return (fileInfo.exists() && fileInfo.isFile());
}

I get following compiler errors:

Error: request for member 'exists' in 'fileInfo', which is of non-class type 'QFileInfo(QFile)'

Error: request for member 'isFile' in 'fileInfo', which is of non-class type 'QFileInfo(QFile)'

Why ? I'm reading through docs over and over again but I can't get it. BTW Qt Creator is suggesting me these methods and completes them. But compiler don't like it.

Kousalik
  • 3,111
  • 3
  • 24
  • 46
  • 6
    Why do you need to construct a file? Simply use QFileInfo::QFileInfo(const QString & file) constructor instead. – vahancho May 29 '14 at 10:27
  • I have just missed the constructor but I don't see the reason why it should do any harm. BUT it actually works when providing the path directly. Any idea why ? I'll appreciate an explanation. – Kousalik May 29 '14 at 10:31
  • 1
    I think compiler treats QFileInfo fileInfo(QFile(path)); as a function declaration and not as an object initialization. – vahancho May 29 '14 at 10:33

3 Answers3

9

It seems vexing parse: compiler thinks that

QFileInfo fileInfo(QFile(path));

is a function definition like QFileInfo fileInfo(QFile path);

Use instead something like:

QFile ff(file);
QFileInfo fileInfo(ff);
bool test = (fileInfo.exists() && fileInfo.isFile());
Community
  • 1
  • 1
asclepix
  • 7,971
  • 3
  • 31
  • 41
  • 1
    Or you could use the aggregate initialisation (http://en.cppreference.com/w/cpp/language/aggregate_initialization): `QFileInfo fileInfo{QFile{path}}`. – Kane Jun 23 '17 at 10:00
0

You can directly use

QFileInfo fileInfo(path)
bool test = fileInfo.exists() && fileInfo.isFile()
0

Due to my low reputation I cannot make comments, then here I put some lines about QFileInfo:

QFileInfo fileInfo("./.py");
bool test = fileInfo.exists() && fileInfo.isFile();

that example will fail!

I added in the check the baseName() value:

bool test = fileInfo.exists() && fileInfo.isFile() && !fileInfo.baseName().isEmpty();
Juampa
  • 1
  • 2