Untitled
unknown
plain_text
a year ago
2.1 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
// Function to traverse the directory recursively
void traverse_directory(const char *dir_path, FILE *output_file) {
struct dirent *entry;
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir failed");
return;
}
while ((entry = readdir(dir)) != NULL) {
// Skip the "." and ".." entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Build the full path to the file or directory
char path[1024];
snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name);
struct stat statbuf;
if (lstat(path, &statbuf) == -1) {
perror("lstat failed");
continue;
}
// Check if it's a regular file
if (S_ISREG(statbuf.st_mode)) {
// Write file size to the output file
fprintf(output_file, "%s: %ld bytes\n", path, statbuf.st_size);
}
// If it's a directory, traverse it recursively
else if (S_ISDIR(statbuf.st_mode)) {
traverse_directory(path, output_file);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
// Check for the correct number of arguments
if (argc != 3) {
fprintf(stderr, "Usage: %s <directory> <output_file>\n", argv[0]);
return EXIT_FAILURE;
}
const char *dir_path = argv[1];
const char *output_file_path = argv[2];
// Open the output file
FILE *output_file = fopen(output_file_path, "w");
if (output_file == NULL) {
perror("fopen failed");
return EXIT_FAILURE;
}
// Start traversing the directory
traverse_directory(dir_path, output_file);
// Close the output file
fclose(output_file);
printf("File sizes written to %s\n", output_file_path);
return EXIT_SUCCESS;
}
Editor is loading...
Leave a Comment