Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Check if file exists Qt



  • hi i tried many ways but lately take me problems? some working example. sorry again..



  • Hi!
    There are several ways to do that. One is using [static] bool QFile::exists(const QString &fileName), e.g.:

    qDebug() << QFile::exists("/home/pw/docs/file.txt");
    


  • Hi,

    You can also use QFileInfo Class to check the existance of file.

    Sample code.

    QString fileName("./sample.txt");
    QFile file(fileName);
    if(QFileInfo::exists(fileName))
    {
        qDebug () << "file exists" << endl;
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        QString data =  file.readAll();
        qDebug () << "data in file:" << data << endl;
        qDebug()<<"file already created"<<endl;
        file.close();
    }
    else
    {
        qDebug () << "file does not exists" << endl;
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        file.write("Qt Programming");
        qDebug()<<"file created"<<endl;
        file.close();
    }
    

    Checks files exists, if not exists, file gets created and data is written to the file.
    If file exists read the data from the file.

    Thanks,



  • As @Wieland said many ways to check

    There are several ways to do that. One is using [static] bool QFile::exists(const QString &fileName), e.g.:

    qDebug() << QFile::exists("/home/pw/docs/file.txt");
    
    QString fileName("./sample.txt");
    QFile file(fileName);
    qDebug () << file.exists();
    

    exists() method with parameter and without parameter.

    Thanks,



  • Another way:

    qDebug() << QDir("/home/pw/docs").exists("file.txt");
    


  • @Wieland said in Check if file exists Qt:

    Another way:

    qDebug() << QDir("/home/pw/docs").exists("file.txt");
    

    Nice Info.


Log in to reply