2009-06-24 87 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)?熟悉这可能需要一段时间,但不是那么多。这可能是值得的投资,并且你的代码将不是平台特定的。