1

I have no idea how to make the code for this command.

I had something but is not working. I think is a problem at the exec.

Can someone make it work?

i'm a newbie in this field.

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

void showArgs(int argc, char *argv[]){
    int i;
    for (i=0;i<argc;i++) {
        printf("Argument is %s ",argv[i]);
    }
}

int main(int argc, char*argv[])
{
int isdir(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}
printf("Program started... \n");
showArgs(argc, argv);
if(argc == 2)
{
    if(isdir(argv[1]))
    {
        printf("Calling dir with parameter\n");
        execl("dirname",argv[1],NULL);
    }else{
        printf("invalid dir name\n");
}
}
return 0;
}
7
  • 1
    What about this isn't working? What results are you seeing; what do you expect? Also, are you sure that simply calling the existing dirname program counts as implementing it?
    – Daniel H
    Commented Jan 15, 2018 at 4:44
  • It dose not print the execl("dirname",argv[1],NULL); Commented Jan 15, 2018 at 4:49
  • Does it print any other line of code? Generally your program will only print things you tell it to, like with the printf statements.
    – Daniel H
    Commented Jan 15, 2018 at 4:52
  • isdir() is defined and called in same main() function, it will not create any problem for you?
    – Achal
    Commented Jan 15, 2018 at 5:06
  • 1
    Shelling out to dirname hardly counts as a way of implementing dirname, at least not in my book.
    – unwind
    Commented Jan 15, 2018 at 9:06

1 Answer 1

2

you're missing an argument to execl(). It should be:

execl("/usr/bin/dirname", "dirname", argv[1], (char*)NULL);

The first argument is the path to the command to execute, then the remaining arguments are the elements of the argv array. And argv[0] is the name of the command.

You can also use execlp(), which searches for the command using the PATH environment variable. Then the first argument can just be "dirname". But you still need to repeat it in argv[0].

Also, functions should not be defined inside other functions in C. The isdir() definition should be before main(), not inside it.

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.