一、C語言中判斷文件是否存在
#include<stdio.h> #include<stdlib.h> #include<io.h> int main() { if(access("test.txt",0)==-1) printf("The file is not exist!"); else printf("The file is exist!"); return 0; }
在C語言中,可以使用access函數來判斷文件是否存在。這個函數其實是一個系統調用,可以看做是一個輕量級的通用訪問函數,它可以用來判斷文件或目錄是否存在。函數原型為:int access(const char *path, int mode);其中第一個參數為文件路徑,第二個參數表示訪問模式,0表示存在即可訪問,-1表示不存在。
二、C語言中判斷文件夾是否存在
#include<stdio.h> #include<stdlib.h> #include<io.h> int main(){ if(_access("C:\\Test",0)==0) printf("The folder is exist!"); else { printf("The folder is not exist!, creating......"); if(_mkdir("C:\\Test") == 0){ printf("Create folder successfully."); } else{ printf("Create folder failed."); } } return 0; }
在C語言中,可以使用_access函數來判斷文件夾是否存在,其實與文件的判斷差不多。如果文件夾不存在,則使用_mkdir函數來創建文件夾。需要注意的是,這裡使用的是Windows系統下的函數,在Linux或者Unix系統下使用不同的函數。
三、Qt中判斷文件是否存在
#include <QFile> #include <QDebug> int main() { QString fileName = "test.txt"; QFile file(fileName); if(file.exists()) qDebug() << "The file is exist!"; else qDebug() << "The file is not exist!"; return 0; }
在Qt中,我們可以使用QFile類來判斷文件是否存在。QFile類提供了exists()函數用於判斷文件是否存在,返回值為bool類型。如果文件存在,該函數返回true,否則返回false。
四、Qt中判斷文件夾是否存在
#include <QDir> #include <QDebug> int main() { QString dirName = "C:/Test"; QDir dir(dirName); if(dir.exists()) qDebug()<<"The folder is exist!"; else{ qDebug()<<"The folder is not exist!, creating......"; if(dir.mkpath(dirName)){ qDebug()<<"Create folder successfully."; }else{ qDebug()<<"Create folder failed."; } } return 0; }
在Qt中判斷文件夾是否存在,我們可以使用QDir類。QDir類提供了exists()函數用於判斷文件夾是否存在,如果存在則返回true,否則返回false。同時,我們也可以使用mkpath函數來創建文件夾。需要注意的是,路徑分隔符在Windows和Linux系統中不同。
五、Qt中判斷文件是否為空
#include<QFile> #include<QTextStream> #include<QDebug> int main() { QString fileName = "test.txt"; QFile file(fileName); if(file.size() == 0){ qDebug()<<"The file is empty."; }else{ QTextStream stream(&file); QString content = stream.readAll(); if(content.isEmpty()){ qDebug()<<"The file is empty."; }else{ qDebug()<<"The file is not empty."<<content; } } return 0; }
在Qt中判斷文件是否為空,我們可以使用QFile類的size()函數來獲取文件大小。如果文件大小為0,則說明文件為空。如果文件不為空,則可以使用QTextStream類來讀取文件內容,然後根據content是否為空來判斷文件是否為空。
六、Qt中判斷目錄是否存在
#include<QDir> #include<QDebug> int main() { QString dirName = "C:/Test"; QDir dir(dirName); if(dir.exists()){ qDebug()<<"The directory exists."; }else{ qDebug()<<"The directory does not exist."; } return 0; }
在Qt中判斷目錄是否存在,我們可以使用QDir類的exists()函數來判斷目錄是否存在。如果目錄存在,則返回true;否則返回false。
七、Qt下判斷文件目錄路徑不存在
#include<QFileInfo> #include<QDebug> int main(){ QString filePath = "C:/Temp/temp.txt"; QFileInfo fileInfo(filePath); QString path = fileInfo.path(); QDir dir(path); if(!dir.exists()){ qDebug()<<"Directory does not exist."; }else{ qDebug()<<"Directory exists."<<path; } return 0; }
在Qt中判斷文件路徑所在的目錄是否存在,我們可以先使用QFileInfo類來獲取文件的路徑,然後使用QDir類來判斷路徑所在的目錄是否存在。
原創文章,作者:FRRUV,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/360821.html