title: How to use execvp() with grep?
body: <p>I am trying to exec() a call to grep inside of my C program. I am looking for the number of occurrences of a string pattern in a given file, which can be achieved with:</p>
  
  <pre><code>$ grep -e my_string -F my_file.txt -c
  </code></pre>
  
  <p>Which gives a number output as expected, such as:</p>
  
  <pre><code>5
  </code></pre>
  
  <p>However, what I hoped would be equivalent seems to be having some difficulties. The following code:</p>
  
  <pre><code>char *arg_list[] = {"-e", "my_string", "-F", "my_file.txt", "-c", "\0"};
  
  int pid;
  if ((pid = fork()) == 0) {
      if (execvp("grep", arg_list) &lt; 0)
          perror("execvp");
  }
  </code></pre>
  
  <p>Results in:</p>
  
  <pre><code> my_file.txt:5
   -e: : No such file or directory
  </code></pre>
  
  <p>There are two issues. First, I just want the number-- not the file in which it is found. Second, I'm not sure why it is trying to assert that the -e flag needs to be a file. If I switch around the argument list to be:</p>
  
  <pre><code>char *arg_list[] = {"-F", "my_file.txt", "-e", "my_string", "-c", "\0"};
  </code></pre>
  
  <p>Then I get back:</p>
  
  <pre><code>my_file.txt:5
  -F: : No such file or directory
  </code></pre>
  
  <p>I'm not sure where to start looking for why this is happening. I'm also not sure why the output of the grep call from the command-line is just a number, but the exec()'d grep call outputs both the filename and number. </p>
  
  <p>Any help would be appreciated! Thank you.</p>
  
  <p>EDIT: </p>
  
  <p>Solution: include the program name in the argument list, or simply use the system() call. Also, RTFM. </p>