Search code examples
cfile-read

fread doesn't read multiple lines


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?


Solution

  • 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 (read > 0) //if return value is > 0
    {
        buffer[page_size]='\0';
        printf("|%s|\n",buffer);
    }
    
    }
    while(read == page_size); //end when a read returned fewer items
    
    fclose(fp);
    

    you can try with this code, this code is running fine.

    I tried with your code and that is also running fine on my system.