Search code examples
coperating-systempipesystem

Piping output of system command to file


I am working on an assignment where I am required to run system commands and write the output to a file. At the moment I am able to pipe the output using the >> output.txt at runtime but how do I do it automatically in my program without having the user type the piping part. I have tried concatenating it in the system function itself while also trying to create a temp variable to append it at the beginning of each loop. I haven't worked with C in years and so a task that is relatively easy I am finding hard. Here is my source code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[]) { /*argc holds the number of arguments and argv is an array of string pointers with indifinate size  */

    /*Check to see if no more than 4 arg entered */
    if(argc > 4 && argc > 0) {
        printf("Invalid number of arguments. No greater than 4");
        return 0;
    }
    FILE *fp;
    int i;
    char* temp[128];

    for(i = 1; i < argc; i++) {
        //strcopy(temp, argv[i]);
    //  printf("%s", temp);
        system(argv[i] >> output.txt);

    }
    return 0;
}

Thanks for all the help.


Solution

  • The >> in this context is not a shell redirect but the C right-shift operator.

    The redirection needs to be part of the command sent to system. Also, temp needs to be an array of char, not an array of char *:

    char temp[128];
    sprintf(temp, "%s >> output.txt", argv[1]);
    system(temp);