File Handling prog explanation

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

argc is the number of cstrings, and argv is the array of cstrings. The first cstring will always be full path of the file "c:\..." , that's why it checks for argc!=2. It gets the parameters when you run it through the console and type something after it, like "myProgram.exe filename".
Last edited on
thanks
just one more thing to clarify my doubt: will argv[1] be storing the file name supplied at run time...?
argv[0] would
Topic archived. No new replies allowed.