variations in fread() buffering

Discussion in 'C' started by Jishnu, Sep 3, 2010.

  1. Jishnu

    Jishnu New Member

    Joined:
    Sep 3, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,

    I was reading Vijaya Mukhi's The 'C' Odyssey UNIX - The Open-Boundless C (1st ed.). This is in reference to program 43 in the first chapter when file buffering is introduced.

    Code:
    int main() {
     FILE *fp;
     char buff[11]; 
     int pid;
     fp=fopen("baby1","r");
     pid=fork();
     if(!pid) {
      printf("initial file handle :: %d\n",ftell(fp));
      fread(buff,sizeof(buff),1,fp);
      buff[10]='\0';
      printf("child read :: %s\n",buff);
      printf("child file handle :: %d\n",ftell(fp));
     }
     else {
      wait((int *)0);
      printf("parent file handle :: %d\n",ftell(fp));
      fread(buff,sizeof(buff),1,fp);
      buff[10]='\0';
      printf("parent read :: %s\n",buff);
      printf("end file handle :: %d\n",ftell(fp));
     }
     return 0;
    }
    
    The contents of baby1 are:
    As per the book, the output should be:

    The book explains this by saying that fread() reads 1024 characters (whatever the block size is) by default into a buffer. Hence the file pointer also moves by 1024 bytes which is reflected because the process is different.

    I tried the same code on Solaris and RHEL and got interesting results.

    Output on Solaris:

    This indicates that in Solaris, block size is the same as specified in the fread() arguments. There is no such thing called default block size.

    Output on RHEL:

    This indicates that in RHEL, block size is a number greater than 26 but the file pointer never exceeds the size of file.

    From what I understood, across various OS'es system calls are different but library calls behave in the same way. Library calls should be system independent which is not the case here. I would like some clarification on this point.

    I would also like to have some idea of how the file buffering takes place internally in case of system calls and library calls.

    Thanks in advance.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice