Skip to content

Instantly share code, notes, and snippets.

@dnutiu
Created October 25, 2017 12:45
Show Gist options
  • Select an option

  • Save dnutiu/619e8878485ccda4f1c8c016829fa29c to your computer and use it in GitHub Desktop.

Select an option

Save dnutiu/619e8878485ccda4f1c8c016829fa29c to your computer and use it in GitHub Desktop.
How to use directories system calls in C
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int OUTPUT_FILE;
void write_to_output(char * path, char * type) {
struct stat *buf = (struct stat *) malloc(sizeof(struct stat));
size_t written = 0;
char * str_buf = (char *) malloc(100);
if ( -1 == stat(path, buf) ) {
fprintf(stderr, "Error opening stat for file: %s\n", path);
perror("err");
return;
}
write(OUTPUT_FILE, path, strlen(path));
write(OUTPUT_FILE, "\n", 1);
write(OUTPUT_FILE, type, strlen(type));
write(OUTPUT_FILE, "\n", 1);
written = sprintf(str_buf, "%lld\n", buf->st_size);
write(OUTPUT_FILE, str_buf, written);
write(OUTPUT_FILE, "\n", 1);
free(str_buf);
free(buf);
}
void scan_directory(char * directory_name) {
DIR * directory = NULL;
struct dirent * directory_entry = NULL;
if (NULL == (directory = opendir(directory_name)) ) {
fprintf(stderr, "Directory open failed %s\n", directory_name);
return;
}
while ( (directory_entry = readdir(directory)) ) {
if (NULL == directory_entry) {
break;
}
char * new_dir_path = (char *) malloc(100);
unsigned char directory_type = directory_entry->d_type; // DT_REG, DT_DIR
if ( DT_REG == directory_type ) {
printf("Regular file %s\n", directory_entry->d_name);
// Write to output file
sprintf(new_dir_path, "%s/%s", directory_name, directory_entry->d_name);
write_to_output(new_dir_path, "Regular File");
} else if ( DT_DIR == directory_type ) {
if ( (0 == strcmp(directory_entry->d_name, ".")) || (0 == strcmp(directory_entry->d_name, "..")) ) {
continue;
}
printf("Directory file %s\n", directory_entry->d_name);
// Write to output file.
write_to_output(directory_name, "Directory");
// Call recursively...
sprintf(new_dir_path, "%s/%s", directory_name, directory_entry->d_name);
scan_directory(new_dir_path);
}
free(new_dir_path);
}
if (closedir(directory)) {
perror("Error closing directory");
exit(EXIT_FAILURE);
}
free(directory_entry);
}
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Invalid usage, 2 arguments needed: directory, outputfile");
return -1;
}
if ( -1 == (OUTPUT_FILE = open(argv[2], O_RDWR | O_CREAT, S_IXUSR | S_IWUSR | S_IRUSR | S_IRWXU))) {
perror("Error opening output file.");
exit(EXIT_FAILURE);
}
printf("DEBUG: scan_directory(%s)\n\n", argv[1]);
scan_directory(argv[1]);
if ( -1 == close(OUTPUT_FILE)) {
perror("Error closing output file.");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment