在 Linux 中,copendir()
函数用于打开一个目录流,以便你可以使用 readdir()
函数读取目录中的条目。要获取目录下文件的大小,你需要结合使用这些函数以及其他一些系统调用,如 stat()
。
下面是一个简单的示例,展示了如何使用 copendir()
、readdir()
和 stat()
来获取目录下每个文件的大小:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[PATH_MAX];
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>
", argv[0]);
return EXIT_FAILURE;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
// Skip current and parent directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct the full path to the file
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// Get file status
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// Check if it's a regular file and print its size
if (S_ISREG(file_stat.st_mode)) {
printf("%s: %ld bytes
", entry->d_name, file_stat.st_size);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
opendir()
打开一个目录流。readdir()
函数读取目录中的每个条目。snprintf()
构建文件的完整路径。stat()
函数获取文件的状态信息,包括大小。S_ISREG()
宏检查条目是否为常规文件。编译并运行这个程序时,传入一个目录路径作为参数,它将输出该目录下所有常规文件的大小。