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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8427436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:33:03  来源:igfitidea点击:

How can I check whether this is directory-path or any filename-path?

clinuxfiledirectory

提问by Jeegar Patel

by this

这样

Why does fopen("any_path_name",'r') not give NULL as return?

为什么 fopen("any_path_name",'r') 不返回 NULL 作为返回值?

i get to know that in linux directories and files are considered to be file. so when i give any directory-path or file-path in fopen with read mode it doesnt give NULL file descriptor and?

我知道在 linux 中目录和文件被认为是文件。因此,当我在 fopen 中以读取模式提供任何目录路径或文件路径时,它不会提供 NULL 文件描述符,并且?

so how can i check that whether it is dirctory path or file-path ? if i am getting some path from command argument?

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

采纳答案by zed_0xff

man 2 stat:

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

回答by Igor Oks

You can use S_ISDIRmacro .

您可以使用S_ISDIR宏。

回答by Jeegar Patel

thanks zed_0xff and lgor Oks

感谢 zed_0xff 和 lgor Oks

this things can be check by this sample code

这件事可以通过这个示例代码来检查

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

output is

输出是

its null
directory