0

I'm writing a C program that functions like a shell. What it does is when user gives it a path, such as /bin, it needs to be able to check if a given executable program is on that path and if so, execute that program. From another question, I know I can check if a file exists using stat() function:

int file_exist (char *filename){
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it such as like this:

if (file_exist ("myfile.txt")) {
  printf ("It exists\n");
}

But I have a path variable:

char* path = "/bin";

How do I search for an executable program is on this path, with the purpose of trying to execute it later on?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Van
  • 145
  • 1
  • 1
  • 11
  • Use `scandir` to get a list of files in a dir -- See this implementation of `ls` : [http://simplestcodings.blogspot.com/2010/09/ls-command-implementation-for-linuxunix.html] Then use `stat` to see if the file is an executable - the st_mode member of the stat structure returned can be logically anded with the `S_IXUSR` bit. – JohnH Mar 08 '18 at 00:31
  • 2
    Or just concatenate the executable name to the path name, and pass that to your "exists" function. But frankly, if all this isn't completely obvious to you, writing a shell is probably too much of a challenge. – Lee Daniel Crocker Mar 08 '18 at 00:39
  • @JohnH Thanks for the suggestion John! That can definitely check if file is an executable! – Van Mar 08 '18 at 01:29
  • @JohnH - The URL you gave in your first comment is broken - looks like the `]` got mixed up into it at the end: `for-linuxunix.html]` – Addison Mar 09 '18 at 01:24
  • @Van The suggestion to concatenate the `path` and the cmd `name` has nothing to do with the simplicity of the shell, You are just using creating a new character array large enough to hold `/bin`, the next `'/'` and finally the command name (with the required `'\0'`). E.g. at least `size_t len = 4 + 1 + strlen(cmd) + 1;` chars) Using a fixed buffer of `PATH_MAX` length is more than enough, `char cmd_w_path[PATH_MAX] = "";`, then just `strcpy (cmd_w_path, "/bin/"); strcat (cmd_w_path, cmd);` and then pass `cmd_w_path` to `if (file_exists(cmd_w_path))...` – David C. Rankin Mar 24 '18 at 03:49

0 Answers0