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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。