2012-04-23 104 views
57

如何檢查文件是否存在於給定的路徑中或不在Qt中?如何用C++檢查Qt文件是否存在

我當前的代碼如下:

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

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

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

+1

我認爲@mozzbozz下面可能有你的答案 - 不要忘了接受/給點:) – Rachael 2015-02-18 16:33:22

回答

1

我將跳過使用任何來自Qt的根本,只是使用舊的標準access

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

@ Styne666:每一個編譯器,我很在Windows上意識到支持「訪問」 - 當然MS和gcc端口。英特爾使用支持它的MS庫,並且Comeau使用後端編譯器的庫。 – 2012-04-23 07:18:51

+0

謝謝你讓我做我的研究。我接受這可能似乎工作,但考慮到[這個答案的評論](http://stackoverflow.com/a/230068/594137)我仍然認爲堅持與Qt的選項(如果你有一個Qt項目)是更好的解決方案。 – 2012-04-23 07:31:22

+2

@ Styne666:我一點都不確定Qt提供了一些解決setuid/setgid程序的問題,這似乎是唯一重要的問題。他們爭論的是「跨平臺」的含義以及關心哪些標準,但如果我們只關心Qt支持的平臺,那麼這些平臺大都是沒有意義的。 – 2012-04-23 07:36:49

8

你已經發布的代碼是正確的。有可能是其他事情是錯的。

嘗試把這樣的:

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

您的HandleError函數中。如果上面的消息打印出來,你就知道還有其他問題。

63

我會用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())?


TL; DR(與上面的功能的短版,節省的幾行代碼)

#include <QFileInfo> 

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

只是一個建議,在功能'布爾FILEEXISTS(常量的QString&路徑)的代碼'可以進一步簡化爲:'返回checkFile.exists()&& checkFile.isFile(); '@mozzbozz – Dreamer 2016-04-04 20:54:19

+0

@Dreamer感謝您的評論。當然你是對的,雖然它也是一個品味問題。我也添加了你的版本(我會在這裏留下更長的版本,因爲初學者可能更容易遵守)。 – mozzbozz 2016-04-12 21:39:45

+1

感謝您的代碼!不過,您需要在「isFile()」之後刪除右括號。 – Alex 2017-01-23 10:52:45

4

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

#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很難檢查數據庫是否存在,因爲它會自動創建一個新的數據庫,如果它不存在。

2

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

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