Link to home
Start Free TrialLog in
Avatar of errang
errangFlag for Afghanistan

asked on

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");
      exit(0);
    }

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

      if(result){
        full = strcat(pathlist->element, "/ls");
        printf("%s\n", full);
        exit(1);
      }
    }
    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.
ASKER CERTIFIED SOLUTION
Avatar of ewest02
ewest02
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of errang

ASKER

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 ????
Avatar of errang

ASKER

yeah, sorry I copy pasted... guess I wasn't looking.