前言 :
在下面範例透過函數 stat 來判斷某個路徑是否存在與如果存在, 是檔案還是目錄.
範例代碼 :
範例程式由使用者從Console 輸入路徑, 接著透過處理判斷該路徑是否存在與類型為檔案或是目錄 :
執行結果 :
補充說明 :
* Check if a file exists using C++
在下面範例透過函數 stat 來判斷某個路徑是否存在與如果存在, 是檔案還是目錄.
範例代碼 :
範例程式由使用者從Console 輸入路徑, 接著透過處理判斷該路徑是否存在與類型為檔案或是目錄 :
- 範例代碼 :
- #include
- #include
- #include
- #include
- using namespace std;
- void main() {
- struct stat stFileInfo;
- bool blnReturn;
- int intStat;
- char cszFilePath[100];
- printf("Please give file path: ");
- scanf("%s", &cszFilePath);
- printf("File path=%s\n", &cszFilePath);
- intStat = stat(cszFilePath, &stFileInfo);
- if(intStat == 0) {
- printf("File Exist!\n");
- if(stFileInfo.st_mode & S_IFREG) {
- printf("Input is regular file.\n");
- } else if(stFileInfo.st_mode & S_IFDIR) {
- printf("Input is directory.\n");
- } else {
- printf("Unknown.\n");
- }
- blnReturn = true;
- } else {
- printf("File not exist!\n");
- blnReturn = false;
- }
- }
執行結果 :
Please give file path: E:/Temp/a.c #輸入路徑
File path=E:/Temp/a.c
File Exist! # 該路徑存在
Input is regular file. #且為檔案
補充說明 :
* Check if a file exists using C++
There are many ways to check if a file exists in C++, however there are some ways which are better. Many people just say you should try to open it and if that fails, it doesn't exist. That method is slightly flawed because in some cases you may just not have permission to read the contents of the file, which is why the open is failing. A better way to check if a file exists is to use the stat() function. This function returns the file attributes of a file and therefore doesn't ever attempt to open it.
This message was edited 1 time. Last update was at 04/08/2010 18:15:15
沒有留言:
張貼留言