C++ 区分C和C+中的unix目录和文件+;

C++ 区分C和C+中的unix目录和文件+;,c++,c,file,unix,directory,C++,C,File,Unix,Directory,给定一个路径,比如/home/shree/path/def,我想确定def是目录还是文件。有没有实现C或C++代码的方法?< /P> < P>使用STAT(2)系统调用。您可以使用st_mode字段上的S_ISREG或S_ISDIR宏查看给定路径是文件还是目录。手册页告诉您所有其他字段。以下代码使用stat()函数和S_ISDIR(“是一个目录”)和S_ISREG(“是一个常规文件”)宏来获取有关该文件的信息。剩下的只是错误检查,足以生成一个完整的可编译程序 #include <stdio

给定一个路径,比如/home/shree/path/def,我想确定def是目录还是文件。有没有实现C或C++代码的方法?< /P> < P>使用STAT(2)系统调用。您可以使用st_mode字段上的S_ISREG或S_ISDIR宏查看给定路径是文件还是目录。手册页告诉您所有其他字段。

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

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

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") ; string test1=“test-e filename”; 如果(!系统(测试1)) printf(“文件名存在”); string test2=“test-d filename”; 如果(!系统(测试2)) printf(“文件名是一个目录”); string test3=“test-f filename”; 如果(!系统(测试3)) printf(“文件名是普通文件”);
但是我担心这只适用于linux。

使用boost::filesystem库及其is_目录(const Path&p)怎么样?可能需要一段时间来熟悉,但不是太多。这可能是值得投资的,而且您的代码不会是特定于平台的。

如果文件名包含空格,则会有问题,我认为您必须避开它。虽然这样做可行,但性能仍有待提高。对system()的每次调用都将分叉,然后执行一个新的shell来解释该命令。由于错误检查,您的代码有点麻烦。我建议删除此项并添加一些注释,如“检查错误:文件不存在,参数不足”。我想这会让你的答案更好。我更喜欢用错误检查,因为这经常被遗漏在例子中,人们不一定知道如何把它放回去。我把它放进去了,但在正文中澄清了重要的部分是什么。 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") ;