Beginners C Programming Challenge
Quote:
Hello,
I have been reading the tutorial for C on this site and I started to work on the first Help Free C programming Challenge(for Beginners) which asks to write a program that takes a file as an argument and counts the total # of lines. I compiled my code on Code::Blocks Mingw compiler and there are many errors. Perhaps someone give suggestions how to get this right. Thanks
UCnLA
Code is as follows:
Code:
#include <stdlib.h> /* Program to count the total # of lines in a file and print result */
#include <stdio.h>
int line_count=0; /* variable for total lines in a file*/
char FILE*fp;
int main(int argc, char* argv[])
{
if(argc != 2)
{
/* We print argv[0], assuming it is the name of the file*/
printf("usage: %s filename", argv[0]);
}
else
{
/* We assume argv[1] is a filename to open*/
char FILE*fp = fopen(argv[1], "r");
/* fopen returns 0, the NULL pointer, on failure */
if ( fp == 0 )
{
printf( "Could not open file\n" );
}
else
{
char x; /* read one character at a time from file,tests for newline, counts total lines, stopping at
(EOF) end of the file). */
while ( ( x = fgetc( *fp ) ) != EOF )
{
if(x = '\n')
{
line_count++;
}
}
line_count++; /* Counts the final line of the file. */
}
printf("There are %d" line_count,"Total Lines in the file known as %s" argv[0]);
fclose( FILE*fp );
}
return(0);
}