S
sosij.morris
The 'spec' is to write a 'whereis' program for Windows. There was no
need to have argv[1] be valid sot hat bit I've added.
The spec also said that to detect an existing file, one could use
anything. As gcc had access() I used that.
Note that I've yet to comment this up - so please don't tell me to do
that - I will.
The question I mostly have is, as this is a short program, is it ok to
have reused 'path'?
Firstly it's assigned the return from getenv(), then the return from
the initial strtok() call, and then it's assigned NULL to keep
strtok() going.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
char const * whereis(char const * const prg)
{
static char filepath[MAX_PATH];
char * path;
path = getenv("PATH");
while((path = strtok(path, ";")) != NULL)
{
strncpy(filepath, path, MAX_PATH);
if(path[strlen(path) - 1] != '\\')
{
strncat(filepath, "\\", MAX_PATH);
}
strncat(filepath, prg, MAX_PATH);
if(access(filepath, X_OK) == 0)
{
return filepath;
}
path = NULL;
}
return NULL;
}
int main(int argc, char * argv[])
{
char const * filepath;
if(argc != 2)
{
puts("Arg required");
}
else
{
if((filepath = whereis(argv[1])) != NULL)
{
puts(filepath);
}
else
{
puts("Not found");
}
}
return 0;
}
need to have argv[1] be valid sot hat bit I've added.
The spec also said that to detect an existing file, one could use
anything. As gcc had access() I used that.
Note that I've yet to comment this up - so please don't tell me to do
that - I will.
The question I mostly have is, as this is a short program, is it ok to
have reused 'path'?
Firstly it's assigned the return from getenv(), then the return from
the initial strtok() call, and then it's assigned NULL to keep
strtok() going.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
char const * whereis(char const * const prg)
{
static char filepath[MAX_PATH];
char * path;
path = getenv("PATH");
while((path = strtok(path, ";")) != NULL)
{
strncpy(filepath, path, MAX_PATH);
if(path[strlen(path) - 1] != '\\')
{
strncat(filepath, "\\", MAX_PATH);
}
strncat(filepath, prg, MAX_PATH);
if(access(filepath, X_OK) == 0)
{
return filepath;
}
path = NULL;
}
return NULL;
}
int main(int argc, char * argv[])
{
char const * filepath;
if(argc != 2)
{
puts("Arg required");
}
else
{
if((filepath = whereis(argv[1])) != NULL)
{
puts(filepath);
}
else
{
puts("Not found");
}
}
return 0;
}