1

I was wondering if someone could tell me what I'm doing wrong. This code is supposed to walk though all the directories and files and print them out exactly the same way the UNIX utility FIND does. But for some reason I cant get chdir to change the working directory. I'm trying to limit the number of file descriptors im using.

MAIN

#include <stdio.h>
#include "sfind.h"
#include <unistd.h>
#include <dirent.h>
int main(int argv, char *argc[]){
    char cwd[1024]; /* current working directory limit*/
    char *path = NULL;
    DIR *dp = NULL;
    if (getcwd(cwd, sizeof(cwd)) != NULL){ /*allow us to grab the current working directory*/
      fprintf(stdout, "Current working dir: %s\n", cwd);
    }
    else{
        perror("getcwd() error");
    }
    dp = opendir(cwd);
    path = ".";
    directoryList(dp,path);
    return 0;
}

Directory Method Definition

#include <stdio.h>
#include <stdlib.h>
#include "sfind.h"
#include <unistd.h>
#include <limits.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

void directoryList(DIR *dp, char *path){
    char newPath[PATH_MAX] = {0};/*To store new path*/
  struct dirent *element; /*get file name*/
  struct stat statbuf;/*determine type of file*/
  int status = 0; /*My base case should be once the directory I'm in runs outs out of files I should return;*/
  if(dp == NULL){
    fprintf(stderr,"FILE DID NOT OPEN!");
    exit(-1);
  }
  /*change the current file directory even if its the first one*/  
  if((status = chdir(path)) == -1){
    printf("ERROOR!");
  }/*change the current working directory whether that the same on or not*/

  while((element = readdir(dp)) != NULL) /*while current file directory pointer is not equal to zero*/{ 
    /* from here we only have two cases once were reading from the directory either is a file or directory!*/
    /*using lstat*/

    lstat(element->d_name,&statbuf);

    if((S_ISDIR(statbuf.st_mode))) /*is of type directory*/{
        if((strcmp(".",element->d_name) == 0) || (strcmp("..",element->d_name) == 0))
        continue;
      /*create new directory name*/
      newPath[0] = '\0';
      strcat(newPath,path);/* this will give us the "."*/
      strcat(newPath,"/");
      strcat(newPath,element->d_name);
      printf("%s\n", newPath);
      directoryList(dp,newPath); /*recursion*/ 
      file*/
    }
    else /*Its a file!*/{
        printf("%s/%s\n",path,element->d_name);
    }
  }
}
7
  • any type of help would be much appreciated May 16, 2017 at 22:45
  • 1
    What error are you seeing?
    – Myst
    May 16, 2017 at 22:49
  • I can't seem to go any deeper then just the first directory @Myst May 16, 2017 at 22:50
  • 3
    Instead of just printing ERROR!, can you print out the error with perror or strerror?
    – Daniel H
    May 16, 2017 at 22:55
  • 2
    In general, you don't want to be using chdir() much if at all in functions like this. chdir() will affect the entire process, which is not good if you're writing library or multithreaded codes. In library code, you don't want to change any state of the process at all, and in multithreaded code using chdir() impacts all threads in the process. May 16, 2017 at 23:12

2 Answers 2

0

The issue seems to be with the call to readdir(dp)...

Even though you change the current working directory, you don't update the dp pointer to open the new folder.

Here's a poor-man's working example (I wouldn't do it this way, but it works for small trees).

#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

void directoryList(DIR *dp, char *path) {
  char newPath[PATH_MAX] = {0}; /*To store new path*/
  struct dirent *element;       /*get file name*/
  struct stat statbuf;          /*determine type of file*/
  int status = 0;               /*My base case should be once the directory I'm in runs outs
                                   out of files I should return;*/
  DIR *dp_tmp;
  if (dp == NULL) {
    fprintf(stderr, "FILE DID NOT OPEN!");
    exit(-1);
  }

  while ((element = readdir(dp)) !=
         NULL) /*while current file directory pointer is not equal to zero*/ {
    /* from here we only have two cases once were reading from the directory
     * either is a file or directory!*/
    /*using lstat*/
    lstat(element->d_name, &statbuf);

    if ((S_ISDIR(statbuf.st_mode))) /*is of type directory*/ {
      if ((strcmp(".", element->d_name) == 0) ||
          (strcmp("..", element->d_name) == 0))
        continue;
      /*create new directory name*/
      newPath[0] = '\0';
      strcat(newPath, path); /* this will give us the "."*/
      strcat(newPath, "/");
      strcat(newPath, element->d_name);
      printf("%s\n", newPath);
      if ((dp_tmp = opendir(newPath)) == NULL) {
        perror("hmm?! ");
        exit(1);
      }
      directoryList(dp_tmp, newPath); /*recursion*/
    } else /*Its a file!*/ {
      printf("* %s/%s\n", path, element->d_name);
    }
  }
  closedir(dp);
}

int main(void) {
  char cwd[1024]; /* current working directory limit*/
  char *path = NULL;
  DIR *dp = NULL;
  if (getcwd(cwd, sizeof(cwd)) !=
      NULL) { /*allow us to grab the current working directory*/
    fprintf(stdout, "Current working dir: %s\n", cwd);
  } else {
    perror("getcwd() error");
  }
  dp = opendir(cwd);
  path = ".";
  directoryList(dp, path);
  return 0;
}

EDIT:

To answer the question in the comment...

Open directories (that should be closed using closedir) are different (and quite unrelated) to the current working directory.

The current working directory is mostly used to resolve the path to any file/folder you're referencing.

Open directory pointers (DIR *) are just pointers to data in the memory. That data relates to a specific directory and you can open a number of directories at the same time.

EDIT2:

A few people in the comments recommended nftw (file tree walk) which is a great alternative to doing it yourself.

If this isn't a learning project, I would recommend it's use.

However, note that POSIX.1-2008 marks ftw as obsolete, so make sure to use the nftw flavor.

3
  • I thought that It would be done in the condition of the while loop. I was under the assumption that chdir would update it after changing the working directory. May 16, 2017 at 23:03
  • Nope. You're changing the working directory, not the open directory. You can open any directory, you don't need to change the working directory for that.
    – Myst
    May 16, 2017 at 23:05
  • @SamuelMagaña, I updates my answer to better reflect your comment.
    – Myst
    May 16, 2017 at 23:14
0

Is your goal to learn to implement this yourself, or do you just want results? Because you should take a look at fts.h if you want some very powerful stuff to implement something like find.

3
  • 1
    fts.h? Do you mean ftw.h? May 16, 2017 at 23:12
  • No, but that would also work. I'm not entirely sure which one is more portable.
    – Cheatah
    May 16, 2017 at 23:25
  • ftw.h is POSIX. fts.h seems to be BSD-heritage. May 17, 2017 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.