fread doesn't read multiple lines

Blenikos picture Blenikos · Mar 15, 2013 · Viewed 7.2k times · Source

I am trying to read from a .txt file that has some numbers in lines.

It looks like that.

example.txt

123
456
789
555

I open this as a binary file for reading wanted to read this file line by line so i know that in every line theres 4 characters (3 numbers and 1 new line character '\n').

I am doing this:

FILE * fp;

int page_size=4;
size_t read=0;
char * buffer = (char *)malloc((page_size+1)*sizeof(char));
fp = fopen("example.txt", "rb"); //open the file for binary input

//loop through the file reading a page at a time
do {
    read = fread(buffer,sizeof(char),page_size, fp); //issue the read call

    if(feof(fp)!=0) 
      read=0;

    if (read > 0) //if return value is > 0
    {   
        if (read < page_size) //if fewer bytes than requested were returned...
        {
            //fill the remainder of the buffer with zeroes
            memset(buffer + read, 0, page_size - read);
        }

        buffer[page_size]='\0';
        printf("|%s|\n",buffer);
    }

}
while(read == page_size); //end when a read returned fewer items

fclose(fp); //close the file

In printf is expected this result then

|123
|
|456
|
|789
|
|555
|

but the actual result i am taking is:

|123
|
456|
|
78|
|9
6|
|66
|

so it looks like that after the first 2 fread it reads only 2 numbers and something goes completely wrong with the new line character.

So what is wrong with fread here?

Answer

Yasir Malik picture Yasir Malik · Mar 15, 2013

You can use the following to read the file line by line.

   FILE * fp;
   char * line = NULL;
   size_t len = 0;
   ssize_t read;

   while ((read = getline(&line, &len, fp)) != -1) {
       printf("Line length: %zd :\n", read);
       printf("Line text: %s", line);
   }