Search code examples
cfopen

Opening a file from command line arguments in C


I want my C program to ask the user to type the name of the file they want to open and print the contents of that file to the screen. I am working from the C tutorial and have the following code so far. But when I execute it, it doesn't actually allow me to enter the file name. (I get the 'press any button to continue', I am using codeblocks)

What am I doing wrong here?

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    printf("Enter the file name: \n");
    //scanf
    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] );
    }
    else
    {
        // We assume argv[1] is a filename to open
        FILE *file = fopen( argv[1], "r" );

        /* fopen returns 0, the NULL pointer, on failure */
        if ( file == 0 )
        {
            printf( "Could not open file\n" );
        }
        else
        {
            int x;
            /* Read one character at a time from file, stopping at EOF, which
               indicates the end of the file. Note that the idiom of "assign
               to a variable, check the value" used below works because
               the assignment statement evaluates to the value assigned. */
            while  ( ( x = fgetc( file ) ) != EOF )
            {
                printf( "%c", x );
            }
            fclose( file );
        }
    }
    return 0;
}

Solution

  • If you want to read user input from a prompt, you would use the scanf() function. To parse command line parameters, you would type them at the command line, as in:

    myprogram myfilename
    

    rather than just typing

    myprogram
    

    and expecting to be prompted. myfilename would be in the argv array when your program starts.

    So, start by removing the printf( "Enter the file name:" ) prompt. The filename would be in argv[ 1 ] assuming you entered it as the first parameter after myprogram on your command line.