#include <stdio.h>
#include <stdlib.h> /* exit, calloc, realloc */
#include <sys/types.h> /* opendir, readdir, lstat */
#include <dirent.h> /* opendir, readdir */
#include <string.h> /* strcmp, strlen */
#include <limits.h> /* PATH_MAX */
#include <sys/stat.h> /* lstat */

#ifndef PATH_MAX
#define PATH_MAX 1024
#endif

void traverse_dir(char*);

int main(int argc, char* argv[]) {
	char *dir_path;
	if(argc != 2) {
		printf("Usage: traverse_dir dir \n");
		exit(1);
	}

	dir_path = argv[1];
	traverse_dir(dir_path);
	exit(0);
}

void traverse_dir(char* dir_path) {
	DIR *dir_ptr;
	struct dirent *dirent_ptr;
	char tmp_path[PATH_MAX];
	struct stat stat_buf;

	dir_ptr = opendir(dir_path);
	if(dir_ptr == NULL) {
		perror(dir_path);
		exit(2);
	}

	while((dirent_ptr=readdir(dir_ptr)) != NULL) {
		if((strcmp(dirent_ptr->d_name, ".") == 0) ||
			(strcmp(dirent_ptr->d_name, "..") == 0)) {
			continue;
		}

		strcpy(tmp_path, dir_path);
		strcat(tmp_path, "/");
		strcat(tmp_path, dirent_ptr->d_name);

		printf("%s\n", tmp_path);

		if(stat(tmp_path, &stat_buf) == -1) {
			perror(tmp_path);
			exit(3);
		}

		if(S_ISDIR(stat_buf.st_mode)) {
			traverse_dir(tmp_path);
		}
	}

	if(closedir(dir_ptr) == -1) {
		perror(dir_path);
		exit(4);
	}
}
