我肯定不是第一个不知道ls是怎么实现的人。
一般大家都知道怎么在linux下打开一个文件,然后读取里面的内容;
不过怎么样遍历一个目录,可能不少人还不太清楚用什么API。
下面是一个简单的ls demo程序,可以演示操作目录的模式。
#include <sys/types.h> #include <dirent.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> int ls(char *sPathName) { DIR *dir = opendir(sPathName); if( dir == NULL ) { printf("open %s fail.\n", sPathName); return -1; } chdir(sPathName); struct dirent *file; while( file = readdir( dir ) ) { #ifdef _DIRENT_HAVE_D_TYPE //如果是普通文件 if( file->d_type & DT_REG ) { struct stat status; stat(file->d_name, &status); printf("%20s last modified time: %d\n", file->d_name, int(status.st_mtime)); } else { continue; } #else #endif } return 0; } int main(int c, char **v) { return ls(v[1]); }
ls的详细实现,可以在这里找到。
近期评论