the code isn't counting correctly as all the numbers in the output are lower than they should be. I can't find any reason as to why I'm getting these numbers as I still don't understand c very well.
if I read in a file with 25 lines and 20 lines excluding white space and comments the output from my code will be 10 and -13 and I'm not sure why. Any help is greatly appreciated.
#include <stdio.h>
#include <string.h>
#define LINE_LENGTH 1000
int main(int argc, char **argv)
{
FILE *input_file = fopen("cstest.c", "r");
char line [LINE_LENGTH];
//while loop to get
while(fgets(line,LINE_LENGTH,input_file)!=NULL)
{
int ch=0;//ch is the cast
int lines=0;
if (input_file == NULL)
return 0;
while(fgetc(input_file)!= EOF)
{
ch = fgetc(input_file);
if(ch == '\n')
{
lines ;
}
}//end while
printf("lines: %d\n",lines);
}//end while loop
rewind(input_file);
while(fgets(line,LINE_LENGTH,input_file)!=NULL)
{
int ch=0;//ch is the cast
int lines=0;
char c;
if (input_file == NULL)
return 0;
while(fgetc(input_file)!= EOF)
{
ch = fgetc(input_file);
if(ch == '\n')
{
lines ;
}
if(ch == '\n' && ch 1 == '\n' || ch == '\t')
{
lines--;
}
}//end while
printf("lines excluding white space and comments: %d\n",lines);
}//end while loop
fclose(input_file);
}
CodePudding user response:
You're skipping lots of things.
First, a line is read by this condition:
while(fgets(line,LINE_LENGTH,input_file)!=NULL)
This line won't be read by the later fgetc()
calls. So you never count the newline at the end of this line.
Then in your next loop:
while(fgetc(input_file)!= EOF)
{
ch = fgetc(input_file);
if(ch == '\n')
{
lines ;
}
}//end while
you only check every other character to see if it's a newline. You read one character in the while()
condition and just check if it's EOF
. Then you read another character in the loop body and test if it's `\n'.
You don't need the nested loops or multiple calls to fgetc()
.
int ch;
while((ch = fgetc(input_file))!= EOF)
{
if(ch == '\n')
{
lines ;
}
}//end while
printf("lines: %d\n",lines);
CodePudding user response:
You only need one loop, fgets
is reading the whole line for you. Barmar fixes it one way , I went the other way.
int lines = 0;
//while loop to get
while (fgets(line, LINE_LENGTH, input_file) != NULL)
{
int ch = 0;//ch is the cast
lines ;
//while (fgetc(input_file) != EOF)
//{
// ch = fgetc(input_file);
// if (ch == '\n')
// {
// lines ;
// }
//}//end while
printf("lines: %d\n", lines);
}//end while loop