a question about which

Hey, I'm trying to write a which function, I've gotten most of it down:

#include "sh.h"
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

int which1(char *dir, char *sub_dir);

int main()
  DIR *pdir;
  struct pathelement *pathlist;
  int i = 0;
  int result;
  struct dirent *pfile;
  char *dir, *subdir, *full;
  pathlist = get_path();
  pdir = opendir("/usr/bin/");

  if(NULL == pdir)
      printf("Error Opening Directory\n");

    while(pfile = readdir(pdir)){
      result = which1(pfile->d_name, "ls");

        full = strcat(pathlist->element, "/ls");
        printf("%s\n", full);
    pathlist = pathlist->next;

  return 0;

int which1(char *dir, char *sub_dir){
 int result = 0;

  if(!(strcmp(sub_dir, dir)))
    result = 1;

  return result;

The actual looping is happening in the main function, the outer loop just checks if pathlist is null or not.

The inner loop is supposed to open the directory and keep sending the 2 parameters to which1, which compares the two strings and returns 1, and 0 if they aren't.

I'm just testing it on ls at the moment, I know I will need to change that string to a variable in my actual program... but what I can't figure out is, why it keeps appending the wrong directory to ls when its printing it.
Who is Participating?
ewest02Connect With a Mentor Commented:
Your outer loop just cycles through the path list, while the inner loop is doing the real work with readdir(). Note that the call to readdir passes pdir which was returned by opendir( "/usr/bin"). When you find the directory entry with "ls" you call strcat() with pathlist->element and "ls". However, the directory scan with readdir() is based on opendir( "/usr/bin") -- not pathlist.

errangAuthor Commented:
That fixed it, and I had to put pdir = opendir("/usr/bin/"); in the loop as well.
You do mean   pdir = opendir( pathlist->element)   yes ????
errangAuthor Commented:
yeah, sorry I copy pasted... guess I wasn't looking.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.