2009-06-24 83 views

回答

35

以下代碼使用stat()函數和S_ISDIR('是目錄')和S_ISREG('是常規文件')宏來獲取有關文件的信息。其餘的只是錯誤檢查,並且足以製作完整的可編譯程序。

#include <stdio.h> 
#include <errno.h> 
#include <sys/stat.h> 

int main (int argc, char *argv[]) { 
    int status; 
    struct stat st_buf; 

    // Ensure argument passed. 

    if (argc != 2) { 
     printf ("Usage: progName <fileSpec>\n"); 
     printf ("  where <fileSpec> is the file to check.\n"); 
     return 1; 
    } 

    // Get the status of the file system object. 

    status = stat (argv[1], &st_buf); 
    if (status != 0) { 
     printf ("Error, errno = %d\n", errno); 
     return 1; 
    } 

    // Tell us what it is then exit. 

    if (S_ISREG (st_buf.st_mode)) { 
     printf ("%s is a regular file.\n", argv[1]); 
    } 
    if (S_ISDIR (st_buf.st_mode)) { 
     printf ("%s is a directory.\n", argv[1]); 
    } 

    return 0; 
} 

樣品試驗如下所示:


pax> vi progName.c ; gcc -o progName progName.c ; ./progName 
Usage: progName 
     where is the file to check. 

pax> ./progName /home 
/home is a directory. 

pax> ./progName .profile 
.profile is a regular file. 

pax> ./progName /no_such_file 
Error, errno = 2 
+0

由於錯誤檢查,您的代碼有點麻煩。我建議刪除這個並添加一些評論,如「檢查錯誤:文件不存在,沒有足夠的參數」。我認爲它會讓你的答案更好一些 – 2009-06-24 07:40:59

+3

我更喜歡錯誤檢查,因爲這經常被排除在示例之外,人們不一定知道如何將它放回去。 – 2009-06-24 08:07:40

9

使用stat(2)系統調用。您可以在st_mode字段上使用S_ISREG或S_ISDIR宏來查看給定路徑是文件還是目錄。手冊頁告訴你所有其他領域。

-1

另外,您可以在內置的shell命令 「測試」 使用system()函數。
系統返回命令的退出狀態最後執行

 
string test1 = "test -e filename" ; 
if(!system(test1)) 
printf("filename exists") ; 

string test2 = "test -d filename" ; 
if(!system(test2)) 
    printf("filename is a directory") ; 

string test3 = "test -f filename" ; 
if(!system(test3)) 
    printf("filename is a normal file") ; 

但恐怕這隻會在Linux上工作..

5

怎麼樣使用升壓::文件系統庫及其is_directory(const的路徑& p)?熟悉這可能需要一段時間,但不是那麼多。這可能是值得的投資,並且你的代碼將不是平臺特定的。