Why does fopen("any_path_name",'r') not give NULL as return?
我结识,在linux下的目录和文件都被认为是文件。所以当我给读取模式fopen任何目录路径或文件路径它不给NULL文件描述符和?
那么我该如何检查它是否是dirctory路径或文件路径?如果我从命令参数获得一些路径?
Why does fopen("any_path_name",'r') not give NULL as return?
我结识,在linux下的目录和文件都被认为是文件。所以当我给读取模式fopen任何目录路径或文件路径它不给NULL文件描述符和?
那么我该如何检查它是否是dirctory路径或文件路径?如果我从命令参数获得一些路径?
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 */
可以使用S_ISDIR
宏。
感谢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
通常文件有扩展名,例如 “* .TXT”,“ * .log“,因此,基于此,你可以知道它是一个文件还是目录,但是等待更好的答案 – ComputerSaysNo
已经问过类似或相同的问题。 请参阅 http://stackoverflow.com/questions/1036625/differentiate-between-a-unix-directory-and-file-in-c和 http://stackoverflow.com/questions/146924/how-can -i-tell-if-a-given-path-is-a-directory-or-a-file-cc – riship89
@DorinDuminica:在UNIX上下文中,依靠后缀来识别任何东西被认为是不好的样式。首先考虑文件属性(如本例中的文件类型),然后尝试使用'file'来标识文件,并且只有在没有其他操作的情况下才会使用扩展名。 – thiton