我正在学习linux中的c编程,我写这个是为了输出文件和目录的信息,比如标准工具“ls”和“-l”,除了宏S_ISDIR,一切都很好,这是我的代码。此外,我的操作系统是 mint 14 x86_64。
#include<sys/types.h>
#include<time.h>
#include<string.h>
#include<dirent.h>
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
void do_ls(char []);
void show_file_info(struct stat *t){
printf("mode: %o\n",t->st_mode);
if(S_ISDIR(t->st_mode)==0)
printf("Is a dir\n");
else
printf("Is not a dir\n");
printf("links: %d\n",t->st_nlink);
printf("group: %d\n",t->st_gid);
printf("user: %d\n",t->st_uid);
printf("size: %d\n",t->st_size);
printf("modtime: %s\n",ctime(&t->st_mtime));
}
int main(int num,char *a[]){
if(num==1){
do_ls(".");
}
else{
while(--num){
printf("%s :\n",*++a);
do_ls(*a);
}
}
}
void do_ls(char dirname[]){
DIR *tem=opendir(dirname);
struct dirent *direntp;
struct stat *buf;
char t[256];
if(tem==NULL){
fprintf(stderr,"ls: cannot open %s\n",dirname);
}
else{
while((direntp=readdir(tem))!=NULL){
strcpy(t,dirname);
printf("%s\n",direntp->d_name);
strcat(t,"/");
if(stat(t,buf)==-1){
perror("");
break;
}
else{
show_file_info(buf);
}
}
closedir(tem);
}
}