该程序实现的是ls -al #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <grp.h> #include <pwd.h> #include <time.h> #include <string.h> #include <dirent.h> //从path中获取文件名 void getFileName(char* fileName, const char* path) { if( NULL==fileName || NULL==path) { printf("in getFileName, args error!/n"); exit(-1) ; } int len=strlen(path); int pos=len-1; while(pos>=0 && path[pos]!='/') { pos--; } strcpy(fileName, path+pos+1 ); } //显示某个文件的详细信息 void showFileInfo(const char* path) { struct stat buf; int ret=lstat(path, &buf); if( -1==ret ) { perror("in showFileInfo, lstat error:"); printf("%s/n", path); return ; } //输出文件类型 //文件类型只判断普通、目录、软链接,其它类似 if( S_ISDIR(buf.st_mode) ) { printf("d"); } else if( S_ISLNK(buf.st_mode) ) { printf("l"); } else { printf("-"); } //输出权限:owner if(S_IRUSR&buf.st_mode ) { printf("r"); } else { printf("-"); } if(S_IWUSR&buf.st_mode) { printf("w"); } else { printf("-"); } if(S_IXUSR&buf.st_mode) { printf("x"); } else { printf("-"); } //输出权限:group if(S_IRGRP&buf.st_mode) { printf("r"); } else { printf("-"); } if(S_IWGRP&buf.st_mode) { printf("w"); } else { printf("-"); } if(S_IXGRP&buf.st_mode) { printf("x"); } else { printf("-"); } //输出权限:others if(S_IROTH&buf.st_mode) { printf("r"); } else { printf("-"); } if(S_IWOTH&buf.st_mode) { printf("w"); } else { printf("-"); } if(S_IXOTH&buf.st_mode) { printf("x"); } else { printf("-"); } //输出一个空格 printf(" "); //输出硬链接数 printf("%d ", buf.st_nlink); //输出用户 struct passwd* pwd=getpwuid(buf.st_uid); printf("%s ", pwd->pw_name); //输出组 struct group* grp=getgrgid(buf.st_gid); printf("%s ",grp->gr_name); //输出文件大小 printf("%d ", (int)buf.st_size); //输出最后一次修改时间 struct tm* t=localtime(&(buf.st_mtime)); printf("%4d-%02d-%02d %02d:%02d ", t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min); //输出文件名 //如果文件是软链接,请同学们自己完善文件名的输出 int len=strlen(path); char* fileName=(char*)malloc(len+1); getFileName(fileName, path); printf("%s", fileName); free(fileName); printf("/n"); } //实现myls的功能 void myls(const char* path ) { DIR* pDir=NULL; struct dirent* pde=NULL; pDir=opendir(path); if( NULL==pDir ) { showFileInfo(path); } else { int ret=chdir(path); if(ret!=0) { perror("in myls, chdir error:"); exit(-1); } while( (pde=readdir(pDir))!=NULL ) { showFileInfo(pde->d_name); } } closedir(pDir); pDir=NULL; } int main(int argc, char *argv[]) { if(argc!=2) { printf("in main, args error!/n"); exit(-1); } myls(argv[1]); return 0; }