[Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 305
  • Last Modified:

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.
  • 2
  • 2
1 Solution
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.

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now