Milan Stephan
Fotografie & IT

Zurück zur SPiC Übersicht

lstree.c

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>


static void die(const char *msg) {
	perror(msg);
	exit(EXIT_FAILURE);
}

static void print_tabs(unsigned int num) {
	for (int i = 0; i < num; i++) {
		printf("\t");
	}
}

static void print_dir(unsigned int depth, const char *folder) {
	DIR *dh = opendir(folder);
	if (dh == NULL) {
		perror(folder);
		return;
		//die(folder);
	}

	struct dirent *d;
	while (errno = 0, (d = readdir(dh))) {

		if (d->d_name[0] == '.') continue;


		char path[strlen(folder) + strlen(d->d_name) + 2];
		strcpy(path, folder);
		strcat(path, "/");
		strcat(path, d->d_name);

		struct stat sb;
		if (lstat(path, &sb) < 0) {
			perror(path);
			continue;
			//die(path);
		}

		if (S_ISREG(sb.st_mode)) {
			print_tabs(depth);
			printf("%s (%u Bytes)\n", d->d_name, (unsigned long) sb.st_size);
		} else if (S_ISDIR(sb.st_mode)) {
			print_tabs(depth);
			printf("%s:\n", d->d_name);
			print_dir(depth + 1, path);
		}
	}
	if (errno != 0) {
		//die(folder);
		perror(folder);
	}

	closedir(dh);
}

int main(int argc, char *argv[]) {
	for (int i = 1; i < argc; i++) {
		printf("%s:\n", argv[i]);
		print_dir(1, argv[i]);
	}
	return EXIT_SUCCESS;
}