Reputation: 13
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;
}
Upvotes: 1
Views: 211
Reputation: 780879
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.
Upvotes: 2