1

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
  • What do you expect `fflush(fp);` to do? Calling `fflush` on an _input_ `FILE*` is generally pretty pointless and the behaviour is implementation dependent. – Jabberwocky Oct 28 '20 at 10:21
  • 1
    @Jabberwocky It's actually [undefined behavior](https://port70.net/~nsz/c/c11/n1570.html#7.21.5.1p2): "If `stream` points to an output stream or an update stream in which the most recent operation was not input, the `fflush` function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; **otherwise, the behavior is undefined.**" – Andrew Henle Oct 28 '20 at 10:56
  • Are you sure that this is the source that produced the described output? It works for me, even if crippled lines because of `fflush()` and the source code as input. Each line is printed with 1 second interval. – the busybee Oct 28 '20 at 11:59
  • @AndrewHenle [fflush(3)](https://man7.org/linux/man-pages/man3/fflush.3.html) states otherwise, but admittedly it's not the standard – Jabberwocky Oct 28 '20 at 12:25
  • @busybee. You are right. Actually it works in a Ubuntu-linux terminal. Due to lack of experience, I executed the program in cygwin and got the behavior described above. In any case, the program shows the same behavior for the flags _IOLBF and _IOFBF, which is still strange to me. – Alexander K. Oct 28 '20 at 16:45

0 Answers0