64 lines
2.1 KiB
C
64 lines
2.1 KiB
C
/*
|
||
Program: dir-all.c (Report comments/bugs to chikh@yuntech.edu.tw)
|
||
Function: 顯示指定目錄內所有檔案之資訊,譬如於命令列輸入 c:\temp\ 檢視效果
|
||
Note:
|
||
1. 本程式使用dirent.h,該標頭檔定義目錄結構的資料型態,該標頭檔位於
|
||
C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include
|
||
2. 命令列輸入的形式原應為 c:\\temp\\ 但實地測試顯示輸入 c:\temp\ 即可正
|
||
確執行,看來毋需在路徑描述的字串中多繕打倒斜線,請同學察覺此細微差異
|
||
3. Dev-C++提供的dirent.h所定義的dirent結構如下:
|
||
struct dirent
|
||
{
|
||
long d_ino; // Always zero
|
||
unsigned short d_reclen; // Always zero
|
||
unsigned short d_namlen; // Length of name in d_name
|
||
char d_name[260];// File name
|
||
};
|
||
*/
|
||
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
#include <dirent.h>
|
||
|
||
int main()
|
||
{
|
||
DIR *dpdf; //宣告路徑型態指標 跟opendir搭配 用來存取開啟路徑的記憶體位置
|
||
struct dirent *epdf;
|
||
char directoryPath[128], fileName[256];
|
||
long i, fileSize, fileCount;
|
||
FILE *fp;
|
||
|
||
system("cls");
|
||
printf("\n輸入目錄夾路徑 ==> ");
|
||
scanf("%127[^\n]%*c",directoryPath);
|
||
|
||
if ((dpdf=opendir(directoryPath)) == NULL) { //opendir後DIR型態去接位置
|
||
printf("目錄不存在!\n");
|
||
return -1;
|
||
}
|
||
printf("目錄內的所有檔案資訊如下 ...\n=============================================\n");
|
||
while (epdf = readdir(dpdf)) { //讀取檔案所在目錄,只要dpdf所指內容不空,即意味著有檔案存在,因此進入迴圈處理
|
||
if (strcmp(epdf->d_name,".")==0 || strcmp(epdf->d_name,"..")==0) continue; //這兩種檔名一定會存在 一定要排除 因為這是系統自動生成的 也會自動隱藏 但再linux不會被隱藏
|
||
sprintf(fileName,"%s%s",directoryPath,epdf->d_name); // 完整路徑+檔名
|
||
if ((fp=fopen(fileName,"rb")) == NULL) { // 開啟檔案,開檔模式為"輸入+輸出+文字非文字通吃"
|
||
//printf("File open error\n");
|
||
printf("%-50s *子目錄*\n",epdf->d_name);
|
||
}
|
||
else {
|
||
fseek(fp,0,SEEK_END); /* 檔案讀寫頭移至最尾端 */
|
||
fileSize = ftell(fp); /* 獲知所在位置,換算為檔案長度 */
|
||
fclose(fp);
|
||
printf("%-50s %d bytes\n",epdf->d_name,fileSize);
|
||
fileCount++;
|
||
}
|
||
}
|
||
|
||
closedir(dpdf); //關閉目錄資料結構
|
||
printf("=============================================\n資料夾內共有%d檔案!\n",fileCount);
|
||
|
||
return 0;
|
||
}
|
||
|
||
|