name name - 3 months ago 12
C Question

Printing to an output file given in command line

How would you print to an output file given by the user in the command line? I know how to print to an output file, but don't know how to get the file when it is given by the user.


You just need to read the name of the file from the input parameters.

The parameters are stored into the array argv of the main. Like this:

#include <stdio.h>

int main ( int argc, char *argv[] )
    if ( argc != 2 ) /* argc should be 2 for correct execution */
        /* We print argv[0] assuming it is the program name */
        printf( "usage: %s filename", argv[0] );
        // We assume argv[1] is a filename to open
        FILE *file = fopen( argv[1], "w" );
        // do something