0

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.

CS_XYZ
  • 33
  • 7

2 Answers2

0

Use !feof (fp1) as your outer while loop condition. Youre not checking for end of file.

Craig Taylor
  • 1,689
  • 1
  • 11
  • 13
  • I don't need to reach the end of file, I terminate earlier when I find the letter E, but I'll this condition for safety – CS_XYZ Mar 19 '17 at 06:12
  • 1
    Ah then strncpy is not null terminating the buffer. Strncpy won't null terminate if reached max characters. Side note: fgetc actually returns an int but because of your unique eof condition you're safe in this example. – Craig Taylor Mar 19 '17 at 06:17
  • Sorry but I did not get your point, I am handling the overflow so it is not supposed to reach the max characters, right? – CS_XYZ Mar 19 '17 at 06:22
  • 1
    Strncpy will not null terminate a string if the num of chars copied is equal to max length. – Craig Taylor Mar 19 '17 at 06:25
  • Note that [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). Don't use `feof(fp1)` as the outer loop condition. – Jonathan Leffler Mar 19 '17 at 07:06
0
buffer = (char*)malloc(sizeof(char)* n);

I just changed your buffer allocation code keeping everything else same. Seems to work fine for me.

Saikat Das
  • 324
  • 2
  • 7
  • [don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Mar 19 '17 at 06:57