Learn C ProgrammingLearn ProgrammingPrograms On Command Line ArgumentsResources

101. Write a program accept a file name from user and print content of that file

By September 18, 2012 September 5th, 2018 No Comments
#include<stdio.h>
int main(int argc, char *argv[])
{
    if ( argc != 2 ){
         printf( "usage: %s filename", argv[0] );
    }
    else 
    {
        FILE *file = fopen( argv[1], "r" );

        if(file == NULL)
             printf("Could not open file\n");
        else 
        {
            int x;
            while((x=fgetc(file)) != EOF)
                 printf( "%c", x );
            fclose( file );
        }
    }
}

Leave a Reply

DEMO01