2012-04-23 106 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 
}