Mar 30, 2009 at 6:47am UTC
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
Mar 30, 2009 at 11:55am UTC
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 Mar 30, 2009 at 11:57am UTC
Mar 31, 2009 at 4:26am UTC
thanks
just one more thing to clarify my doubt: will argv[1] be storing the file name supplied at run time...?