This blog is under construction

Friday 6 April 2012

setvbuf example in C

Header file:
     stdio.h

Synopsis:
     int setvbuf(FILE *stream, char *buf, int mode, size_t size);

Description:
     Controls stream buffering operation.  There are 3 types of buffering:
_IOFBF - full buffering
_IOLBF - line buffering
_IONBF - no buffering.

Returns 0 on success, non-zero on error.

setvbuf function C example:


  #include<stdio.h>
  int main() {
        FILE *fp;
        char buf[100], str[100];
        fp = fopen("file.txt", "r+");
        if (fp == NULL){
                printf("File not found\n");
                return;
        }
        setvbuf(fp, buf, _IONBF, 0);
        fputs("Hello world ", fp);
        fputs("Hello world", fp);
        rewind(fp);
        fgets(str, 12, fp);
        fgets(buf, 12, fp);
        printf("str: %s\n", str);
        printf("buf: %s\n", buf);
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ls
  a.out   file.txt
  jp@jp-VirtualBox:~/$ ./a.out
  str: Hello world
  buf: Hello world


Here, we have used no buffering.  So, input/output operations are performed without any delay.  Whereas, line buffering writes data only when it detects any new line or buffer is full.  Full buffering writes data to its associated stream when the buffer of specified size is filled.  Consider the following example

Eg: setvbuf(fp, buf, _IOFBF, 1024);
fp       -    file pointer
buf      -  data to fp stream is stored in buf until buffer is filled(1024 bytes).  Once 
              buffer is filled, data would be written to the associated stream
_IOFBF - full buffering
1024     -  Size of buffer

In the above example, the data to stream fp is stored in the specified buffer buf.  Once the buffer is filled(1024 bytes), data would be written to the associated stream fp.

No comments:

Post a Comment