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
char singleline;//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
printf("hi\n");// to check that before each line hi is printed?
(till the end)
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
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.
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.