簡體   English   中英

如何在C ++中檢查文件在Qt中是否存在

[英]How to check whether file exists in Qt in c++

如何檢查文件是否在給定的路徑或不存在的Qt?

我當前的代碼如下:

QFile Fout("/Users/Hans/Desktop/result.txt");

if(!Fout.exists()) 
{       
  eh.handleError(8);
}  
else
{
  // ......
}

但是,當我運行代碼時,即使我在路徑中提到的文件不存在,也不會給出handleError指定的錯誤消息。

(TL; DR在底部)

我將使用QFileInfo -class( docs )-這正是它的用途:

該QFileInfo類提供系統無關的文件信息。

QFileInfo提供有關文件的名稱和在文件系統中的位置(路徑),其訪問權限的信息,以及它是否是一個目錄或符號鏈接等文件的大小和最后修改/讀取時間也可提供。 QFileInfo也可以用來獲得有關Qt的資源信息。

這是檢查文件是否存在的源代碼:

#include <QFileInfo>

(不要忘記添加相應#include語句來)

bool fileExists(QString path) {
    QFileInfo check_file(path);
    // check if file exists and if yes: Is it really a file and no directory?
    if (check_file.exists() && check_file.isFile()) {
        return true;
    } else {
        return false;
    }
}

還要考慮:你只需要檢查是否存在的路徑( exists()或者你也想確保,這是一個文件,而不是一個目錄( isFile()

小心 :的文檔exists() -函數說:

如果文件存在,則返回true;否則,返回false。 否則返回false。

注意:如果file是指向不存在文件的符號鏈接,則返回false。

這不是精確的。 它應該是:

如果路徑(即文件或目錄)存在,則返回true;否則,返回true。 否則返回false。


TL; DR

(與上面的功能的較短的版本,節省的幾行代碼)

#include <QFileInfo>

bool fileExists(QString path) {
    QFileInfo check_file(path);
    // check if path exists and if yes: Is it really a file and no directory?
    return check_file.exists() && check_file.isFile();
}

TL; DR Qt的> = 5.2

(使用existsstatic這是在Qt的5.2引入;文檔說的靜態函數是快,但我不知道這仍然還使用時的情況isFile()方法,至少這是一個班輪然后)

#include <QFileInfo>

// check if path exists and if yes: Is it a file and no directory?
bool fileExists = QFileInfo::exists(path) && QFileInfo(path).isFile();

您可以使用QFileInfo::exists()方法:

#include <QFileInfo>
if(QFileInfo("C:\\exampleFile.txt").exists()){
    //The file exists
}
else{
    //The file doesn't exist
}

如果你希望它返回true只有當該文件存在與false ,如果路徑存在,但是是一個文件夾,你可以結合它QDir::exists()

#include <QFileInfo>
#include <QDir>
QString path = "C:\\exampleFile.txt";
if(QFileInfo(path).exists() && !QDir(path).exists()){
    //The file exists and is not a folder
}
else{
    //The file doesn't exist, either the path doesn't exist or is the path of a folder
}

你已經發布的代碼是正確的。 可能還有其他問題。

嘗試把這樣的:

qDebug() << "Function is being called.";

在handleError函數內部。 如果上述消息版畫,你知道的東西是別的問題。

這就是我如何檢查數據庫是否存在:

#include <QtSql>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QFileInfo>

QString db_path = "/home/serge/Projects/sqlite/users_admin.db";

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(db_path);

if (QFileInfo::exists(db_path))
{
    bool ok = db.open();
    if(ok)
    {
        qDebug() << "Connected to the Database !";
        db.close();
    }
}
else
{
    qDebug() << "Database doesn't exists !";
}

隨着SQLite很難檢查數據庫是否存在,因為如果它不存在,它會自動創建一個新的數據庫。

我將完全跳過使用Qt中的任何內容,而僅使用舊的標准access

if (0==access("/Users/Hans/Desktop/result.txt", 0))
    // it exists
else
    // it doesn't exist

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM