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;
}
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
a.out file.txt
jp@jp-VirtualBox:~/$ ./a.out
str: Hello world
buf: Hello world
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