我正在编写一个程序来检查某些东西是文件还是目录.有没有比这更好的方法呢?
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
int isFile(const char* name)
{
DIR* directory = opendir(name);
if(directory != NULL)
{
closedir(directory);
return 0;
}
if(errno == ENOTDIR)
{
return 1;
}
return -1;
}
int main(void)
{
const char* file = "./testFile";
const char* directory = "./";
printf("Is %s a file? %s.\n", file,
((isFile(file) == 1) ? "Yes" : "No"));
printf("Is %s a directory? %s.\n", directory,
((isFile(directory) == 0) ? "Yes" : "No"));
return 0;
}
Run Code Online (Sandbox Code Playgroud) 给定一个路径,比如/ home/shree/path/def,我想确定def是目录还是文件.有没有办法在C或C++代码中实现这一点?