Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening a file from command line arguments in C

Tags:

c

fopen

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;
}
like image 472
TylarBen Avatar asked Feb 26 '12 00:02

TylarBen


1 Answers

This will read from stdin the filename. Perhaps you only want to do this if the filename is not supplied as a part of the command line.

int main ( int argc, char *argv[] ) 
{ 
    char filename[100];
    printf("Enter the file name: \n"); 
    scanf("%s", filename);

    ...
    FILE *file = fopen( filename, "r" );  
like image 190
Ed Heal Avatar answered Sep 20 '22 11:09

Ed Heal