Sunil Kumar Sunil Kumar -4 years ago 78
C Question

fgets not working properly

I wanted to learn how fgets works. For this I wrote code to print "hi" before every line, which is going to be printed from an another text file named input.txt using fgets.

But it is showing 2

hi
s between consecutive lines instead of 1. I can't understand why?

My code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char singleline[150];//storing each line of input.txt as singleline arrays.
FILE *fp;//file pointer named fp.
fp=fopen("input.txt","r");//reading the text file input.txt
while (!feof(fp)){
fgets(singleline,150,fp);
printf("hi\n");// to check that before each line hi is printed?
puts(singleline);
}

return 0;
}


My text file


rohit sharma,batsman,1,35.0,40.0,2200,20,95
viru,batsman,2,28.0,45.0,1800,02,75
suresh raina,batsman,3,38.0,35.0,2300,15,98
suryaky,batsman,4,30.0,0.0,500,0,10
abd,batsman,5,37.2,0.0,1200,0,50
dhoni,batsman,6,45.2,0.0,2100,0,85
albie,allrounder,7,24.87,27.65,945,80,86
ashwin,bowler,8,8.82,24.37,150,82,85
naraine,bowler,9,6.67,16.94,40,67,49
johnson,bowler,10,12.25,21.33,98,45,33
starc,bowler,11,14.17,28.71,85,14,14


Output


hi
rohit sharma,batsman,1,35.0,40.0,2200,20,95

hi
hi
viru,batsman,2,28.0,45.0,1800,02,75
(till the end)
johnson,bowler,10,12.25,21.33,98,45,33

hi
hi
starc,bowler,11,14.17,28.71,85,14,14


What is the error here?

Answer Source

What you posted gives:

hi
rohit sharma,batsman,1,35.0,40.0,2200,20,95  

hi
viru,batsman,2,28.0,45.0,1800,02,75  

as expected, since you do not eat the trailing newline. You can do it by adding this line after reading into singleline.

if(strlen(singleline) != 0) // because you may have an empty file
  singleline[strlen(singleline) - 1] = '\0';

You could also do it like alk suggested:

singleline[strcspn(singleline, "\n")] = 0;

taken from this answer.

Also feof() in the control statement of the while loop makes me redirect you to this question: Why is while ( !feof (file) ) always wrong?

Thanks alk and iharob for the useful comments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download