在Debian系統中,readdir函數通常用于讀取目錄中的文件和子目錄
sudo apt-get update
sudo apt-get install build-essential
readdir_example.c的C文件,并在其中編寫以下代碼:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
printf("Name: %s\n", entry->d_name);
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
printf("\n");
}
closedir(dir);
return 0;
}
這段代碼會讀取指定目錄中的所有文件和子目錄,并輸出它們的名稱、大小和最后修改時間。
gcc readdir_example.c -o readdir_example
./readdir_example /path/to/directory
程序將輸出指定目錄中所有文件和子目錄的名稱、大小和最后修改時間。