'paths must precede expression: `>' in find of execvp c code

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void){
    char *argv[6] = {"/home", "-name", "'*.txt'", ">", "all_txt_files.txt", NULL};
    printf("%s\n", argv[2]);    
    execvp("find", argv);
    return 0;
}

If I run the in the bash find /home -name '*.txt' > Jerry.txt that works just fine. But when I run the c code above, it always gives an error /home: paths must precede expression: `>' Looks like nonsense, can someone help? Using WSL 1 in windows 10.

c


Solution 1:[1]

Think of your example from the viewpoint of the find program. When find is started using your execvp, it gets in its argv vector the following parameters:

  1. /home
  2. -name
  3. '*.txt'
  4. '>'
  5. all_txt_files.txt
  6. NULL

When you invoke find from the command line, the shell sets up the redirection and find sees the following parameters:

  1. /home
  2. -name
  3. *.txt
  4. NULL

As you can see, the parameters differ in number and content. It is not a surprise that you get a different outcome.

Do do the same in your shell program, you would have either to mimic what the shell is doing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1934428