I would like to make my own program who will be work as which command in linux. Original which command works that (example for pwd):
$ which pwd
/bin/pwd
but my program works that:
$ ./prog1 pwd
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games pwd
Can You correct my program? Source code:
#include <sys/param.h>
#include <sys/stat.h>
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *systemPath, *path, *fileName;
struct stat statStruct;
if (argc < 2){
printf( "Nothing to don");
return -1;
}
if ((systemPath = getenv("PATH")) == NULL)
{
perror( "Not found PATH!n ");
return -1;
}
fileName = argv[1];
printf("%s %sn", systemPath, fileName);
while ((path = strsep(&systemPath, ":")) != NULL)
{
if ((stat(fileName, &statStruct) == 0) && S_ISREG(statStruct.st_mode) && (statStruct.st_mode & S_IRUSR))
{
printf("%sn", fileName);
printf("%sn", systemPath);
printf("%sn", path);
}
}
return 0;
}
Advertisement
Answer
You find the candidate directory using strsep, storing it in path. But then you don’t use this variable; the stat call just uses the base filename, which will therefore always be looked up in the current working directory.
You need to form the concatenation of path, a /, and the filename, and then stat that.
You will probably find snprintf useful.