在Ubuntu中,你可以使用readdir
函数来读取目录中的文件和子目录。但是,readdir
本身并不直接提供文件属性。要获取文件属性,你需要结合stat
函数来实现。
以下是一个简单的示例,展示了如何在C语言中使用readdir
和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");
exit(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("File: %s, Size: %ld bytes\n", entry->d_name, file_stat.st_size);
}
closedir(dir);
return 0;
}
这个示例程序会打开当前目录,然后使用readdir
函数读取目录中的每个条目。对于每个条目,它使用stat
函数获取文件属性,并输出文件名和文件大小。注意,你需要包含dirent.h
和sys/stat.h
头文件来使用这些函数。