Linux 系统编程--查看目录文件
2017-09-08 15:39
302 查看
1、打印目录下所有文件及文件夹
#include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> int main(int argc,char **argv) { DIR* pDir; struct dirent* pDirInfo; if (argc == 2) { if (0 != chdir(argv[1])) { printf ("error num is : %d\n",errno); switch(errno) { case EACCES: printf("search permission is denied for one of the components of path\n"); break; case EIO: printf ("I/O error occurred\n"); break; case ENOENT: printf("No such file or directory\n"); break; case EPERM: printf ("Operation not permitted\n"); break; } return errno; } pDir = opendir(argv[1]); } else { pDir = opendir("."); } //打印当前目录 printf ("current directory is : %s\n",getcwd(NULL,0)); if (NULL == pDir) { perror("open dir failed !"); return -1; } pDirInfo = readdir(pDir); while (pDirInfo) { printf("--------------------------------\n"); printf("name: %s \n",pDirInfo->d_name); pDirInfo = readdir(pDir); //遍历文件夹 } closedir(pDir); return 0; }
2、遍历文件夹内容,包括子文件夹
//以树形结构的形式打印指定目录下的所有文件 #include <unistd.h> #include <stdio.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <stdlib.h> #include <errno.h> void printDir1(const char * path, unsigned int depth); int main(int argc, char * *argv) { char *topDir = getcwd(NULL, 0); if (argc == 2) { topDir = argv[1]; } printf("遍历的目录为: %s\n", topDir); printDir1(topDir, 0); return 0; } void printDir1(const char * path, unsigned int depth) { DIR *pDir = opendir(path); if (NULL == pDir) { perror("路径打开失败!"); return; } struct dirent *entry; struct stat statbuf; chdir(path); char *curPath = getcwd(NULL,0); if (!curPath) { perror("curPath == NULL "); return; } while (NULL != (entry = readdir(pDir))) { stat(entry->d_name,&statbuf); char *desPath = (char*)malloc(strlen(curPath) + strlen(entry->d_name) + 2); sprintf(desPath,"%s/%s",curPath,entry->d_name); if (S_ISDIR(statbuf.st_mode)) { if ((strcmp(".",entry->d_name) == 0) || (strcmp("..",entry->d_name) == 0)) continue; printf("%d级--这是目录: %s\n",depth,desPath); printDir1(desPath,depth+1); } else { printf("%d级--这是文件: %s\n",depth,desPath); } free (desPath); } chdir(".."); closedir(pDir); printf("\t*****%d级目录%s--遍历完成**********\n",depth,path); }
相关文章推荐
- linux系统编程之文件与I/O(三):目录的操作
- linux 系统,查看某目录下有多少个文件
- linux下查看系统是32位还是64位,删除文件或者目录,查看ip配置命令
- Linux系统下ACM时间查看修改和文件目录权限处理
- Linux 系统的简单介绍,分区讲解,查看命令,文件目录内容
- linux文件系统,目录管理,文件管理,日期时间,查看文本的常用命令
- linux系统编程之文件与IO(四):目录访问相关系统调用
- Linux系统编程:获取指定目录下指定文件类型的数量
- linux系统 常见/常用基础命令之 文件目录管理(创建,删除,查看,)
- [代码实例][Linux系统编程]遍历目录并且输出目录下文件MD5值
- Linux系统目录结构以及文件查看cat命令的一些小细节
- 将Linux系统的多个目录及文件备份并压缩到一个文件,以方便查看和维护
- linux下查看系统是32位还是64位,删除文件或者目录,查看ip配置命令
- [代码实例][Linux系统编程]列出目录下的文件和子目录
- Linux下的C编程实战(二)――文件系统编程 推荐
- linux的文件系统 目录结构
- Linux编程常用的函数(十一) 系统数据文件和信息
- linux笔记02(查询系统帮助与查找文件或目录)
- Linux 查看磁盘分区、文件系统、使用情况的命令和相关工具介绍
- 文件系统管理 之 Linux 查看磁盘分区、文件系统、使用情况的命令和相关工具介绍