Linux c/c++之目录文件与普通文件的判断
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc,char* argv[]){
struct stat st = {0};
int ret = stat(argv[1],&st);
if(ret){
printf("获取文件%s状态失败!\n",argv[1]);
}
else{
printf("获取文件%s状态成功!\n",argv[1]);
if(S_ISDIR(st.st_mode)){
printf("目录文件1!\n");
}
else{
printf("普通文件1!\n");
}
if(st.st_mode & S_IFDIR){
printf("目录文件2!\n");
}
else{
printf("普通文件2!\n");
}
if((st.st_mode & S_IFMT) == S_IFDIR){
printf("目录文件3!\n");
}
else{
printf("普通文件3!\n");
}
}
return 0;
}
Linux中使用了st_mode字段中的4位来标识文件类型位,因此使用st_mode & S_IFMT就可以提取出文件类型,同时也可以使用S_ISDIR(st_mode)宏将其简化使用  上方代码运行结果 
|