How to make the _IOLBF option in setvbuf to work

306 Views Asked by At

There are many examples on the web on how to use fully buffered/unbuffered streams using the setvbuf utility. However, I am struggling with the line-buffered option.

Suppose, we have a textfile "nums.txt" containing two lines of int numbers.

>$ cat nums.txt
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19

I want to read the file and output the stream to stdout using the line-buffered options.

Observation: Both lines are printed at once.

Expected behavior: The first line will be printed to stdout and then (after one second) the second.

here is the code:

int main(int argc, char *argv[]) {
  
  FILE *fp;
  int BUFSIZE = 25;
  char buffer[BUFSIZE];
  
  if (argc != 2) {
     fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
     return 1;
     }
  else { fp = fopen(argv[1], "r");
       
    setvbuf ( fp , buffer, _IOLBF , BUFSIZE );
    while (fgets(buffer, sizeof(buffer), fp) != 0)
    {   
    fputs(buffer, stdout);
    fflush(fp);
    sleep(1);
    }
    
    fclose (fp);   
    }
    
return 0;
}

The program can be called by

>$ ./myprogram nums.txt
0

There are 0 best solutions below