【问题标题】:Differentiate between a unix directory and file in C and C++区分 C 和 C++ 中的 unix 目录和文件
【发布时间】:2010-11-05 09:59:55
【问题描述】:

给定一个路径,例如 /home/shree/path/def,我想确定 def 是目录还是文件。有没有办法在 C 或 C++ 代码中实现这一点?

【问题讨论】:

    标签: c++ c file unix directory


    【解决方案1】:

    以下代码使用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
    

    【讨论】:

    • 由于错误检查,您的代码有点麻烦。我建议删除它并添加一些评论,例如“检查错误:文件不存在,没有足够的参数”。我想这会让你的答案更好一点
    • 我更喜欢它带有错误检查,因为这通常被排除在示例之外,人们不一定知道如何将它放回原处。
    • 我把它留在了,但在文本中澄清了重要的部分。
    【解决方案2】:

    使用 stat(2) 系统调用。您可以在 st_mode 字段上使用 S_ISREG 或 S_ISDIR 宏来查看给定路径是文件还是目录。手册页会告诉您所有其他字段。

    【讨论】:

      【解决方案3】:

      如何使用 boost::filesystem 库及其 is_directory(const Path& p) ?可能需要一段时间才能熟悉,但不会太多。它可能值得投资,而且您的代码不会是特定于平台的。

      【讨论】:

        【解决方案4】:

        或者,您可以将 system() 函数与内置的 shell 命令“test”一起使用。
        系统返回上次执行命令的退出状态

        string test1 = "test -e 文件名" ; 如果(!系统(test1)) printf("文件名存在") ; string test2 = "test -d 文件名" ; 如果(!系统(test2)) printf("文件名是目录") ; string test3 = "test -f 文件名" ; 如果(!系统(test3)) printf("文件名是普通文件") ;

        但恐怕这只适用于 linux..

        【讨论】:

        • 如果文件名包含空格会出现问题,我认为您必须对其进行转义。
        • 虽然这可行,但性能仍有很多不足之处。对 system() 的每次调用都会分叉,然后执行一个新的 shell 来解释命令。
        猜你喜欢
        • 2012-04-13
        • 2013-12-09
        • 1970-01-01
        • 1970-01-01
        • 2010-10-28
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多