Results 1 to 4 of 4

Thread: Question about "fgets" and buffer sizes

  1. #1
    Join Date
    Apr 2009
    Beans
    268
    Distro
    Xubuntu 16.04 Xenial Xerus

    Question about "fgets" and buffer sizes

    According to my copy of K&R the library function "fgets" has the following prototype and, at most, maxline-1 characters will be read:
    Code:
     char *fgets(char *line, int maxline, FILE *fp)
    Then why does the following program work at all? First, BUFFSIZE is only 2 in malloc, and second, the fgets function is returning the complete line length of all the lines even when maxline (BUFFSIZE) is only 2.

    Here is the output of the program which reads and prints itself:
    Code:
    $ ./a.out
    /*******************
    * Program: popen.c *  
    *******************/
    #include <stdio.h>
    #include <stdlib.h>
    
    // BUFFSIZE changed for debugging only! Normally would be 256.
    #define  BUFFSIZE  2
    
    int main() 
    {
        FILE *in;
        char *buff = malloc( BUFFSIZE * (sizeof(char)) );
    
        if(!(in = popen("cat popen.c", "r"))){
            exit(1);
        }
    
        while(fgets(buff, BUFFSIZE, in)!=NULL){
            printf("%s", buff);
        }
    
        pclose(in);
        free(buff);    
        return 0;
    }

  2. #2
    Join Date
    Aug 2010
    Location
    Lancs, United Kingdom
    Beans
    1,306
    Distro
    Ubuntu Mate 16.04 Xenial Xerus

    Re: Question about "fgets" and buffer sizes

    Quote Originally Posted by donsy View Post
    Then why does the following program work at all? First, BUFFSIZE is only 2 in malloc, and second, the fgets function is returning the complete line length of all the lines even when maxline (BUFFSIZE) is only 2.
    It works because each call to fgets in your program reads a single character (BUFFSIZE-1 is 1). Perhaps you are expecting the rest of the line to be discarded, but that isn't what fgets does. If you add an extra character after each print you will see this extra character after every character in the file.
    Code:
        while(fgets(buff, BUFFSIZE, in)!=NULL){
            printf("%s.", buff);
        }

  3. #3
    Join Date
    Apr 2009
    Beans
    268
    Distro
    Xubuntu 16.04 Xenial Xerus

    Re: Question about "fgets" and buffer sizes

    Thanks, I guess I got too hung up on the "line" part of the "maxline" in the prototype.

  4. #4
    squakie is offline I Ubuntu, Therefore, I Am
    Join Date
    Oct 2012
    Beans
    2,238
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Question about "fgets" and buffer sizes

    Easy to demostrate as well - put a \n at the end of the printf.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •