Search code examples
cstringpathstrtokstat

How can I implement functionality like the program which?


I'd like to find if the program less is installed on the system. I'm not allowed to use a direct system("which less") because of my requirements. So I'm going to try the PATHs in the PATH variable and do stat on the files to see if less is installed. But how do I append less to each of my PATHs? I started with this code

pathValue = getenv ("PATH");
if (! pathValue) {
    printf ("'%s' is not set.\n", "PATH");
}
else {
    printf ("'%s' is set to %s.\n", "PATH", pathValue);
}

Now it correctly prints my PATH but I don't know how to proceed. Can you help me? I think that I must tokenize my pathValue, how can I do that?

$ ./a.out 'PATH' is set to /home/developer/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games.

Solution

  • I believe, the getenv ("PATH"); returns a pointer to the string like,

    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
    

    Clearly, we can see, the different directory paths are : delimited. So,

    1. You can start tokenizing the pathValue using strtok() and : as demiliter. Each resulting token should act as a directory path to check for the file.
    2. Check the existance using stat().