/* Program: folder-info.c (Report comments/bugs to chikh@yuntech.edu.tw) Function: 以遞迴的方式顯示指定目錄內所有檔案與檔案夾之資訊 Note: 本程式使用dirent.h,該標頭檔定義目錄結構的資料型態,該標頭檔位於 C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include */ #include #include #include #include #define MaxSize 256 int chopPos(char *dirPath) { int i, count, len = strlen(dirPath); if (dirPath[len-1] != '\\') { dirPath[len] = '\\'; dirPath[len+1] = '\0'; } for (i = len-1, count = 0; i > 0 && count < 2; i--) if (dirPath[i]=='\\') count++; return i+2; } void showDirectory(char *folderPath, int level) { DIR *dpdf; struct dirent *epdf; char fileName[2*MaxSize], nextLevelDir[128][768], *pstr, indent[2*MaxSize]={0}; long fileSize, fileCount, i, dirCount = 0; FILE *fp; if ((dpdf=opendir(folderPath)) == NULL) { /* 開啟目錄資料結構 */ printf("目錄%s不存在!\n",folderPath); return; } pstr = folderPath+chopPos(folderPath); if (level==0) { printf("%s\n",pstr); sprintf(indent,"%s%s",indent,"| "); } else { for (i = 0; i < level-1; i++) sprintf(indent,"%s%s",indent,"| "); printf("%s+---%s\n",indent,pstr); sprintf(indent,"%s%s",indent,"| | "); } while (epdf = readdir(dpdf)) { /* 讀取檔案所在目錄,只要dpdf所指內容不空,即意味著有檔案存在,因此進入迴圈處理 */ if (strcmp(epdf->d_name,".")==0 || strcmp(epdf->d_name,"..")==0) continue; /* 排除目錄中的 . 與 .. (當下目錄與上一層目錄) */ sprintf(fileName,"%s%s",folderPath,epdf->d_name); // 完整路徑+檔名 if ((fp=fopen(fileName,"rb")) == NULL) { // 開啟檔案,開檔模式為"文字非文字通吃" sprintf(nextLevelDir[dirCount++],"%s\\",fileName); } else { fclose(fp); printf("%s%s\n",indent,epdf->d_name); fileCount++; } } closedir(dpdf); /* 關閉目錄資料結構 */ if (fileCount > 0) { if (level==0) printf("%s(↑上有%d檔案)\n%s\n",indent,fileCount,indent); else { printf("%s(↑上有%d檔案)\n",indent,fileCount); for (i = 0; i < strlen(indent)-4; i++) putchar(indent[i]); printf("\n"); } } if (dirCount > 0) { for (i = 0; i < dirCount; i++) showDirectory(nextLevelDir[i],level+1); } return; } int main() { char directoryPath[MaxSize]; printf("\n輸入目錄夾路徑 ==> "); scanf("%255[^\n]%*c",directoryPath,0); printf("檔案夾%s資訊如下\n",directoryPath); showDirectory(directoryPath,0); return 0; }