0

I want to execute the following shell comand inside a C program:

find <folder_name> -name "*.bin" | wc -l

and store the result in a variable which I have declared inside my program. I don't want the result that indicates if the command executed succesfully, I want the result that tells me how many files ending in .bin exist in my directory. The following code obciously is not working.

char command[10];
command = system("find <folder_name> -name \"*.bin\" | wc -l")

I need to pass the <folder_name> as a command line argument.

How can I accomplish both of these tasks ? I would really appreciate any help.

1 Answers1

1

Retrieving standard output of a subprocess

There's no single function like that in standard C lib. Using system you could redirect stdout to a file then read it using fopen from stdio.h.

To avoid using the filesystem, you could use the POSIX popen: http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html

#include <stdio.h>
FILE *popen(const char *command, const char *mode);

Passing arguments to a subprocess

If you use system you could use standard string manipulation, e.g., sprintf to produce the shell command line. This is a little bit brittle if you have special characters in your arguments (whitespace, quotes, etc.)

To pass the arguments directly you could use the POSIX execl, also mentioned in the documentation for popen above.

szym
  • 5,606
  • 28
  • 34