如何检查这是目录路径还是文件名路径?

4

通过这个

为什么使用fopen("any_path_name",'r')时不会返回NULL?

我了解到在Linux中,目录和文件都被视为文件。因此,当我在fopen中以读取模式给出任何目录路径或文件路径时,它不会返回NULL文件描述符,那么怎么检查它是目录路径还是文件路径?如果我从命令参数中获取一些路径呢?


通常文件有扩展名,例如“*.txt”、“*.log”,因此,基于这个你可以知道它是一个文件还是目录,但请等待更好的答案。 - user497849
已经有类似或相同的问题被提出。请参考以下链接:https://dev59.com/pnNA5IYBdhLWcg3wQ7Uwhttps://dev59.com/MXVC5IYBdhLWcg3w51vy - hrishikeshp19
1
在UNIX环境中,依赖后缀来识别任何东西被认为是不好的风格。首先考虑文件属性(比如这种情况下的文件类型),然后尝试使用“file”命令来识别文件,只有在没有其他方法可行时才会退而求其次使用扩展名。 - thiton
3个回答

6

man 2 stat:

NAME
     fstat, fstat64, lstat, lstat64, stat, stat64 -- get file status

...

     struct stat {
         dev_t           st_dev;           /* ID of device containing file */
         mode_t          st_mode;          /* Mode of file (see below) */

...

     The status information word st_mode has the following bits:

...

     #define        S_IFDIR  0040000  /* directory */

2
您可以使用S_ISDIR宏来进行操作。

2

感谢 zed_0xff 和 lgor Oks

这些东西可以通过此示例代码检查

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat statbuf;

FILE *fb = fopen("/home/jeegar/","r");
if(fb==NULL)
    printf("its null\n");
else
    printf("not null\n");

stat("/home/jeegar/", &statbuf);

if(S_ISDIR(statbuf.st_mode))
    printf("directory\n");
else
    printf("file\n");
return 0;
}

输出结果为

its null
directory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接