CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2009
    Posts
    5

    Explanation of the program that reads files and displays them

    Hi all
    I was trying to understand file handling in Cpp. I came accross the followig code:

    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
    {
    FILE *fp;
    char ch;
    if(argc!=2) {
    printf("You forgot to enter the filename.\n");
    exit(1);
    }
    if((fp=fopen(argv[1], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
    }
    ch = getc(fp); /* read one character */
    while (ch!=EOF) {
    putchar(ch); /* print on screen */
    ch = getc(fp);
    }
    fclose(fp);
    return 0;
    }

    Overall prog is clear to me but i dont understand following:

    int main(int argc, char *argv[])

    I have never seen main in this form. can anyone explain me the parameters and their purpose?

    if(argc!=2) {
    printf("You forgot to enter the filename.\n");
    exit(1);
    }

    What is happening in the above code snippet?

    thanks in advance for replies.....
    Regards

  2. #2
    Join Date
    Mar 2009
    Location
    Bulgaria
    Posts
    63

    Re: Explanation of the program that reads files and displays them

    That's the another standard way of declaring main. This way you can use the arguments, passed to your program. argc is the number of the arguments (the first one, e.g. [0] is always the name of your program) and the following items in the array argv are the arguments. For example, if your program is called fileReader and you execute it this way:
    fileReader my_file.txt
    then argv[0] woulb be fileReader, argv[1] would be my_file.txt and argc would be 2. That's the way your program wants to be called.

  3. #3
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: Explanation of the program that reads files and displays them

    int main(int argc, char *argv[])

    I have never seen main in this form. can anyone explain me the parameters and their purpose?
    This was called command line arguments where user supplied argument to the program upon startup and mostly use in command line environment.
    Thanks for your help.

  4. #4
    Join Date
    Mar 2009
    Posts
    5

    Re: Explanation of the program that reads files and displays them

    thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured