- #1
FYAD
- 5
- 0
I'm very new to programming in c, and I'm trying to write a program that recursivley lists all the files in a directory, as well as all of the subdirectores and their files. I'm having some problems.
On my first go I was able to get all of the files of the current directory to be listed. That was easy. I'm having trouble getting my program to jump into all of the subdirectories and then get back to the original directory and list its files. My code seems to jump into the first subdirectory and list its files, but it ends with a Segmentation fault. I googled the error and found out what it means, but I have no idea how to go about remedying it.
On my first go I was able to get all of the files of the current directory to be listed. That was easy. I'm having trouble getting my program to jump into all of the subdirectories and then get back to the original directory and list its files. My code seems to jump into the first subdirectory and list its files, but it ends with a Segmentation fault. I googled the error and found out what it means, but I have no idea how to go about remedying it.
Code:
#include <stdio.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <dirent.h>
#include <unistd.h>
int x = 0;
struct dirent *dp;
void listit(DIR *dirp,DIR *tdirp,int level){
errno = 0;
if (!(dp = readdir(dirp))) {
if (errno == 0) {
printf("porblem\n");
}
else {
printf("Error reading entry in directory\n");
return;
}
}
else {
tdirp = (opendir(dp->d_name));
if(tdirp){
if(!((strcmp(dp->d_name,".")) == 0 || strcmp(dp->d_name,"..") == 0)){
printf("-----------NEW DIRECTORY--------------\n");
printf(" %s\n",dp-> d_name);
dirp = opendir(dp->d_name);
listit(dirp,tdirp,level);
}
else{
printf("%s\n",dp->d_name);
listit(dirp,tdirp,level);
}
}
printf("%s\n",dp->d_name);
listit(dirp,tdirp,level);
}
}
int main(int argc, char *argv[]){
struct timeval t;
int i, status = 0;
int count = 0;
int level = 0;
DIR *dirp;
DIR *tdirp;
dirp = opendir(argv[1]);
if (argc < 2) { exit(-1); }
if ((status = gettimeofday(&t,0)) != 0) {
printf("Error - time call failed\n");
}
if (!dirp) {
if (access(argv[1],F_OK)) {
printf("Error - couldn't interpret %s as directory.\n", argv[1]);
printf("----------------------------------\n\n");
}
else {
printf("%s\n", argv[1]);
printf("----------------------------------\n\n");
}
}
else {
printf("Contents of directory %s:\n", argv[1]);
listit(dirp,tdirp,level);
}
}