0

I am making a system call with a string variable search that basically calls the /bin/ls with an appended variable provided by the use, e.g., ls file1.

I want to repeat this action when the standard output includes an error message because the name of the input file was not present in the current directory (what would be produced if calling the command from the shell, e.g.: ls: No such file or directory).

The following code works, however, every time it runs—whether the file is present or not—it prints extra information like the errors or the file name. My conclusion has been that it's because the system(search) function runs and is printing to stdout.

How can I avoid printing the system call, but still repeat the it? Can I use the stdout of the system call instead, grab it, copy it to a string variable, and use it as the result to start/end the loop?

while (system(search) != 0) {
    if (system(search) == 0) {
        printf("\nFile <%s> was found succesfully in current directory\n\n",reference);
    }

    printf("\nPlease re-enter reference genome file name:  ");
    scanf("%s", reference);

    strcpy(search, ""); //Empty string
    strcpy(search, ls);
    strcat(search, reference); //Re-insert ls command appending NEW reference input
}
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
bretonics
  • 383
  • 6
  • 18
  • 4
    [`man 3 popen`](http://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html) –  Sep 30 '13 at 16:38
  • possible duplicate of [C++ system() function - How to collect the return value of the issued command?](http://stackoverflow.com/questions/1583234/c-system-function-how-to-collect-the-return-value-of-the-issued-command) – timrau Sep 30 '13 at 16:45
  • man access. Instead of system(), just call access() with the name of the file. Avoid all the overhead of system() or popen(). – Charlie Burns Sep 30 '13 at 16:57
  • Use `popen`, and mind you: error messages go to `stderr`, not `stdout`. – Fred Foo Sep 30 '13 at 17:10
  • 1
    possible duplicate of [Getting output of a system command from stdout in C](http://stackoverflow.com/questions/11840833/getting-output-of-a-system-command-from-stdout-in-c) – Joseph Quinsey Feb 17 '14 at 17:27

0 Answers0