在 Ubuntu 中,你可以使用 C 語言的 dirent.h
庫來讀取目錄中的文件,并使用 stat()
函數來獲取文件的大小。以下是一個簡單的示例代碼,演示如何實現這一功能:
#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 path[1024];
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 獲取文件狀態
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 輸出文件名和大小
printf("File: %s, Size: %ld bytes\n", entry->d_name, file_stat.st_size);
}
// 關閉目錄
closedir(dir);
return EXIT_SUCCESS;
}
打開目錄:使用 opendir()
函數打開當前目錄(.
)。
讀取目錄條目:使用 readdir()
函數遍歷目錄中的每個文件和子目錄。
跳過特殊條目:跳過 .
和 ..
這兩個特殊的目錄條目。
構建文件路徑:使用 snprintf()
函數構建文件的完整路徑。
獲取文件狀態:使用 stat()
函數獲取文件的狀態信息,包括文件大?。?code>st_size 字段)。
輸出文件信息:打印文件名和大小。
關閉目錄:使用 closedir()
函數關閉目錄。
編譯并運行這個程序,你將看到當前目錄中所有文件的名稱和大小。確保你有權限訪問這些文件和目錄。