Originally Posted by
jrdoran
How do I write a program to count the number of characters in an external file. I have most of it down , this is what I have so far:
Good first poke.
Code:
char c;
/* ... */
while( (c = fgetc( file )) != EOF ) //not sure if this is right.
Since fgetc returns an int, c should be an int.
Code:
printf( "Enter the name of a file to show: " );
fgets( fileName, sizeof( fileName ), stdin );
I like to add an fflush(stdout); after the prompt to make sure I can see it.
Code:
if( fileName[strlen( fileName ) -1] == '\n' );
fileName[strlen( fileName ) -1] = '\0';
I believe what ssharish2005 was saying is what the FAQ shows.
Code:
file = fopen( filename, "r" );
Depending on your needs, you may want to open the file in binary mode ("rb").
Code:
if( file == NULL )
{
printf( "Unable to open file: %s\n", fileName );
return( 1 );
}
EXIT_FAILURE, EXIT_SUCCESS, or 0 would be standard.
Code:
while( (c = fgetc( file )) != EOF ) //not sure if this is right.
{
/* probably a good place to increment your counter */
}