程式扎記: [C++ 範例代碼] 如何判斷輸入路徑的檔案/目錄是否存在

標籤

2010年8月4日 星期三

[C++ 範例代碼] 如何判斷輸入路徑的檔案/目錄是否存在


前言 :
在下面範例透過函數 stat 來判斷某個路徑是否存在與如果存在, 是檔案還是目錄.

範例代碼 :
範例程式由使用者從Console 輸入路徑, 接著透過處理判斷該路徑是否存在與類型為檔案或是目錄 :
- 範例代碼 :
  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5.   
  6. using namespace std;  
  7. void main() {  
  8.     struct stat stFileInfo;  
  9.     bool blnReturn;  
  10.     int intStat;  
  11.     char cszFilePath[100];  
  12.     printf("Please give file path: ");  
  13.     scanf("%s", &cszFilePath);  
  14.     printf("File path=%s\n", &cszFilePath);  
  15.     intStat = stat(cszFilePath, &stFileInfo);  
  16.     if(intStat == 0) {  
  17.         printf("File Exist!\n");  
  18.         if(stFileInfo.st_mode & S_IFREG) {  
  19.             printf("Input is regular file.\n");  
  20.         } else if(stFileInfo.st_mode & S_IFDIR) {  
  21.             printf("Input is directory.\n");  
  22.         } else {  
  23.             printf("Unknown.\n");  
  24.         }  
  25.         blnReturn = true;  
  26.     } else {  
  27.         printf("File not exist!\n");  
  28.         blnReturn = false;  
  29.     }  
  30. }  

執行結果 :
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

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!