Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
1.9 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    const char *directory = argv[1];
    struct stat statbuf;

    if (stat(directory, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) {
        printf("The provided path 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;
}
Leave a Comment