在Ubuntu中,你可以使用readdir
函數來讀取目錄中的文件和子目錄。但是,readdir
本身并不直接提供文件大小信息。要獲取文件大小,你需要結合其他函數,如stat
。
以下是一個簡單的示例,展示了如何在Ubuntu中使用C語言和readdir
以及stat
函數來獲取目錄中文件的大?。?/p>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
dir = opendir("."); // 打開當前目錄
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
// 跳過當前目錄和上級目錄的特殊條目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 構建文件的完整路徑
char file_path[1024];
snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);
// 獲取文件狀態
if (stat(file_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 輸出文件名和大小
printf("%s: %ld bytes\n", entry->d_name, file_stat.st_size);
}
closedir(dir);
return EXIT_SUCCESS;
}
這個程序首先打開當前目錄(.
),然后使用readdir
遍歷目錄中的每個條目。對于每個條目,它構建文件的完整路徑,并使用stat
函數獲取文件的狀態信息。stat
結構體中的st_size
字段包含了文件的大?。ㄒ宰止潪閱挝唬?。最后,程序輸出每個文件的名稱和大小。
要編譯并運行此程序,請將其保存為get_file_size.c
,然后在終端中執行以下命令:
gcc get_file_size.c -o get_file_size
./get_file_size
這將顯示當前目錄中所有文件的大小。