C语言实现ls命令
2015-08-26 20:28
1141 查看
#include<stdio.h> #include<unistd.h> #include<sys/stat.h> #include<dirent.h> #include<string.h> #include<sys/types.h> void list_func(char*path,int depth) { DIR*pDirHandle= opendir(path); struct dirent * dent ; struct stat fstat ; if(pDirHandle==NULL) { printf("OpenDir %s Error!\n",path); exit(0); } chdir(path); while((dent=readdir(pDirHandle))!=NULL) { //error then return -1 lstat(dent->d_name,&fstat); if(S_ISDIR(fstat.st_mode)) { //remove director . and .. if(strcmp(".",dent->d_name)==0|| strcmp("..",dent->d_name)==0 ) continue ; printf("%*s%s/\n",depth,"",dent->d_name) ; list_func(dent->d_name,depth+4) ; }else printf("%*s%s\n",depth,"",dent->d_name); } chdir(".."); closedir(pDirHandle); } int main(int argc,char**argv) { char *pDirPath; if(argc==1) { pDirPath = "."; } else{ pDirPath=argv[1]; } int depath=0; printf("List Begin:\n"); list_func(pDirPath,depath) ; printf("List End.\n"); return 0 ; }
这里用到的库文件,和opendir等函数,和stat结构体等。需要看源码或查资料理解。
相关文章推荐
- C++类型转换
- MySql C++调用库Connector/c++编译 和 接口封装【一】mysql数据库安装
- C语言(7)--高精度加法、减法、乘法、今天是星期几、四位平方数、候选人选票问题
- C++强制类型转换操作符 dynamic_cast
- C/C++编程题之整数转IP地址
- C++内联函数总结
- C语言(6)--国际象棋棋盘、螺旋矩阵、指定年份日历、打印ASCII码表
- C++中的指针和指针的引用
- 重读C语言---基本知识 与概念 笔记
- C++动态申请内存 new T()与new T[]的区别
- C++动态申请内存 new T()与new T[]的区别
- 浅谈cin>>与cin.getline读取缓冲区中的‘\n’和空格的区别
- C语言copy文件
- C语言中的运算符
- c++ 可重载运算符和不可重载运算符
- OutMan——C语言中文件的操作
- c++中不能重载的运算符
- c/c++ 取得当前目录
- C语言基础知识之(八):二维数组,二维字符串数组,代码安全
- C++中的error C2662,const的this指针问题