#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
FILE *fp;
fp=fopen("mydata.txt","r");
if(fp==NULL)
{
perror("Error while opening");
exit(0);
}
char *s=(char*)malloc(100);
while(feof(fp)!=EOF)
{
fscanf(fp,"%[^\n]",s);
printf("%s",s);
}
return 0;
}
I am trying to read a file line by line.I am getting infinite loop.Where it has gone wrong ?
You can use the following code to do it.
Your problems were that you weren’t checking the return from
fscanfand that you weren’t actually reading the newline (so the next time you read, you wouldn’t go to the next line).However, if all you’re after is the ability to input and process lines,
fgetsis a better solution thanfscanfsince there’s no chance of buffer overflow:Sample runs with ‘hello’, CTRLD, and a string that’s too big: