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

C 如何检查这是目录路径还是任何文件名路径?,c,linux,file,directory,C,Linux,File,Directory,由此 我知道在linux中,目录和文件被认为是文件。所以,当我在fopen中以读取模式给出任何目录路径或文件路径时,它不会给出空文件描述符,并且 那么我如何检查它是目录路径还是文件路径呢?如果我从命令参数中获得一些路径?man 2 stat: NAME fstat, fstat64, lstat, lstat64, stat, stat64 -- get file status ... struct stat { dev_t st_

由此

我知道在linux中,目录和文件被认为是文件。所以,当我在fopen中以读取模式给出任何目录路径或文件路径时,它不会给出空文件描述符,并且


那么我如何检查它是目录路径还是文件路径呢?如果我从命令参数中获得一些路径?

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 */

您可以使用宏。

谢谢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;
}

通常文件有扩展名,即“.txt”、“.log”,因此,基于此,您可以知道它是文件还是目录,但等待更好的答案类似或相同的问题已经提出。请参阅和@DorinDuminica:在UNIX上下文中,依赖后缀来标识任何内容被认为是不好的风格。首先考虑文件属性(如本例中的文件类型),然后尝试<代码>文件>代码>识别文件,只有在没有其他工作的情况下才退还扩展。@谢谢,谢谢。
its null
directory