This blog is under construction

Friday, 6 April 2012

setbuf example in C

Header file:
     stdio.h

Synopsis:
     void setbuf(FILE *stream, char *buf);

Description:
     Buffering is turned off, if buf is NULL.  Otherwise, it performs the same operation as setvbuf(stream, buf, _IOFBF, BUFSIZE).

For better understanding on setbuf(), please check the below link.


setbuf function C example:


  #include<stdio.h>
  #include <time.h>
  int main() {
        FILE *fp;
        time_t t1, t2, t3;
        char buf[1024];
        setbuf (stdout, buf);
        t1 = time(NULL);
        fprintf(stdout, "hello world\n");
        sleep(5);
        fprintf(stdout, "hello world\n");
        sleep(5);
        t2 = time(NULL);
        printf("time difference(t2 - t1): %ld seconds\n", t2 - t1);
        fflush(stdout);
        fprintf(stdout, "hello world\n");
        sleep(5);
        t3 = time(NULL);
        printf("time difference(t3 - t1): %ld seconds\n", t3 - t1);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world
  time difference(t2 - t1): 10 seconds
  hello world
  time difference(t3 - t1): 15 seconds


The above program would buffer the data to stdout until it detects fflush().  Once fflush() is called, data inside the buffer is printed to standard output.
  hello world
  hello world
  time difference(t2 - t1): 10 seconds

Then, again the program keeps buffering the data to stdout.  When the program execution comes to an end, the remaining data in buffer is printed on the output screen.
  hello world
  time difference(t3 - t1): 15 seconds

setbuf(stdout, buf) is equivalent to setvbuf(fp, buf, _IOFBF, 1024)
Here, the data to stream stdout is stored in the specified buffer buf.  Once the buffer is filled(1024 bytes)/ fflush() is called, data would be written to the associated stream stdout.


setbuf function C example - buffering is turned off:


  #include<stdio.h>
  int main() {
        char *buf = NULL, str[100];
        FILE *fp;
        fp = fopen("mastering-c.txt", "r+");
        /* buffering is turned off - since buf is NULL */
        setbuf(fp, buf);
        fputs("Hello world", fp);
        rewind(fp);
        fgets(str, 30, fp);
        printf("str: %s\n", str);
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  str: Hello world


No comments:

Post a Comment