Help me plz

#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 == 0 )
        {
            printf( "Could not open file\n" );
        }
        else 
        {
            int x;
                        while  ( ( x = fgetc( file ) ) != EOF )
            {
                printf( "%c", x );
            }
            fclose( file );
        }
    }
}

Just replace the condition from line 5 with this one: if ( argc < 2 ) and it should work fine.
Tested on Linux: Ubuntu, and on win 7.
On further posts, please post the question as well, because we can't guess that...

Edited 4 Years Ago by Lucaci Andrew

I'm going to guess you meant to post something more like this:

#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 == 0) {
            printf("Could not open file\n");
        } else {
            int x;
            while ((x = fgetc(file)) != EOF) {
                printf("%c", x);
            }
            fclose(file);
        }
    }
}

Now, did you have a question? Here are some good questions you might consider asking:

  • "When I run this with the wrong number of arguments, it terminates immediately and the usage message doesn't display! What am I doing wrong?"
  • "This program runs too slowly when I use it on large files. Can you suggest ways to speed it up?"
  • "I tried to use this program in a shell script, but I can't tell from testing $? whether it succeeded or not. How do I make my program return a meaningful value?"
This article has been dead for over six months. Start a new discussion instead.