【发布时间】:2010-11-05 09:59:55
【问题描述】:
给定一个路径,例如 /home/shree/path/def,我想确定 def 是目录还是文件。有没有办法在 C 或 C++ 代码中实现这一点?
【问题讨论】:
给定一个路径,例如 /home/shree/path/def,我想确定 def 是目录还是文件。有没有办法在 C 或 C++ 代码中实现这一点?
【问题讨论】:
以下代码使用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
【讨论】:
使用 stat(2) 系统调用。您可以在 st_mode 字段上使用 S_ISREG 或 S_ISDIR 宏来查看给定路径是文件还是目录。手册页会告诉您所有其他字段。
【讨论】:
如何使用 boost::filesystem 库及其 is_directory(const Path& p) ?可能需要一段时间才能熟悉,但不会太多。它可能值得投资,而且您的代码不会是特定于平台的。
【讨论】:
或者,您可以将 system() 函数与内置的 shell 命令“test”一起使用。
系统返回上次执行命令的退出状态
但恐怕这只适用于 linux..
【讨论】: