I need to read line by line from a file here is my code:
FILE *fp1;
char c;
int n = 500;
int counter = 0 ;
char *buffer;
buffer = (char*) realloc(buffer, n);
strcpy(buffer, "");
fp1 = fopen("text.txt","r");
if(fp1 == NULL)
{
perror("Error in opening file");
return;
}
do
{
c = fgetc(fp1);
//My specification .. stop reading if you read E
if( c == 'E' )
{
break ;
}
if (c == '\n') {
printf("%s\n", buffer);
counter=0;
strcpy(buffer, "");
}
else{
counter++;
/*handling overflow*/
if (counter > n) {
n+=100;
buffer = (char*) realloc(buffer, n);
}
strncat(buffer, &c,1);
}
}while(!feof (fp1));
The problem is the code does not work correctly, it prints more line than the original text file. Could anyone help in fining out why?
P.S. I know there are alternatives for getc()
but I need to use it.
UPDATE
I changed the initializing for the buffer from original into this:
char *buffer = NULL;
& all the other strcpy()
to this:
*buffer = NULL;
but still the same problem.