首页 > 代码库 > Linux下扫描目录把所有的普通文本列入列表里面
Linux下扫描目录把所有的普通文本列入列表里面
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/stat.h>#include <dirent.h>#include <unistd.h>const static int STRARRAYLEN=256;typedef char StringBuffer[STRARRAYLEN];typedef struct StringList_t StringList;struct StringList_t{ StringBuffer sb; StringList *next; StringList_t() { next = 0; memset(sb, 0, sizeof (sb)); //sb[0]=‘\0‘; } ~StringList_t() { StringList *itor = this->next; while (itor != NULL) { this->next = itor->next; delete itor; itor = this->next; } }};void OutputList(StringList *list) { StringList *itor = list; while (itor != 0) { printf("%s\n", itor->sb); itor = itor->next; }}int ScanFilesToList(char* folderPath, StringList *fileList) { //get rid of ‘/‘ within folderPath int slen = strlen(folderPath); if (folderPath[slen - 1] == ‘/‘) { folderPath[slen - 1] = ‘\0‘; } StringBuffer pwd = ""; getcwd(pwd, sizeof (pwd)); if (strncmp(folderPath, "..", 2) == 0) { char pwdbak[200] = ""; strcpy(pwdbak, pwd); chdir(folderPath); memset(pwd, 0, sizeof (pwd)); getcwd(pwd, sizeof (pwd)); strcpy(folderPath, pwd); strcpy(pwd, pwdbak); } else { chdir(folderPath); } DIR *dir = opendir(folderPath); if (dir == NULL) { printf("failed to open dir <%s> \n", folderPath); } struct dirent *dt = NULL; struct stat statbuf; while (dt = readdir(dir)) { if (‘.‘ == dt->d_name[0]) { continue; } lstat(dt->d_name, &statbuf); if (S_ISDIR(statbuf.st_mode)) { StringBuffer sb = ""; sprintf(sb, "%s/%s", folderPath, dt->d_name); chdir(sb); ScanFilesToList(sb, fileList); chdir(".."); } else if (S_ISREG(statbuf.st_mode)) { //addfiles to list StringList *tmp=new StringList; sprintf(tmp->sb,"%s/%s", folderPath, dt->d_name); tmp->next=fileList->next; fileList->next=tmp; } } chdir(pwd); return 0;}
Linux下扫描目录把所有的普通文本列入列表里面
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。