Untitled
unknown
plain_text
a year ago
2.0 kB
8
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
// Function to calculate the size of a directory
long get_directory_size(const char *directory) {
struct dirent *entry;
struct stat statbuf;
long total_size = 0;
DIR *dp = opendir(directory);
if (dp == NULL) {
perror("opendir");
return 0;
}
while ((entry = readdir(dp)) != NULL) {
// Skip the "." and ".." entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// Construct the full path
char path[1024];
snprintf(path, sizeof(path), "%s/%s", directory, entry->d_name);
// Get the file or directory status
if (stat(path, &statbuf) == -1) {
perror("stat");
continue;
}
// If it's a file, add its size
if (S_ISREG(statbuf.st_mode)) {
total_size += statbuf.st_size;
}
// If it's a directory, recursively calculate its size
else if (S_ISDIR(statbuf.st_mode)) {
total_size += get_directory_size(path);
}
}
closedir(dp);
return total_size;
}
int main() {
// Get the current working directory
char directory[1024];
if (getcwd(directory, sizeof(directory)) == NULL) {
perror("getcwd");
return 1;
}
printf("Calculating the size of the current working directory: %s\n", directory);
struct stat statbuf;
if (stat(directory, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) {
printf("The current working directory is not a directory or does not exist.\n");
return 1;
}
long size_in_bytes = get_directory_size(directory);
double size_in_megabytes = size_in_bytes / (1024.0 * 1024.0);
printf("Total size of all files in the directory '%s' and its subdirectories is: %ld bytes\n", directory, size_in_bytes);
printf("Total size in megabytes: %.2f MB\n", size_in_megabytes);
return 0;
}
Editor is loading...
Leave a Comment