通过这个
为什么使用fopen("any_path_name",'r')时不会返回NULL?
我了解到在Linux中,目录和文件都被视为文件。因此,当我在fopen中以读取模式给出任何目录路径或文件路径时,它不会返回NULL文件描述符,那么怎么检查它是目录路径还是文件路径?如果我从命令参数中获取一些路径呢?
通过这个
为什么使用fopen("any_path_name",'r')时不会返回NULL?
我了解到在Linux中,目录和文件都被视为文件。因此,当我在fopen中以读取模式给出任何目录路径或文件路径时,它不会返回NULL文件描述符,那么怎么检查它是目录路径还是文件路径?如果我从命令参数中获取一些路径呢?
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;
}
输出结果为
its null
directory