文件流緩衝區


extern void setbuf(FILE *__restrict __stream, char *__restrict __buf, int __ modes, size_t __n)

此函數第一個參數爲要操作的流對象,第2個參數buf必須指向一個長度爲BUFSIZE的緩衝區,如果將buf設置爲NULL,則關閉緩衝區。

如果執行成功,將返回0, 否則返回非0值。


setvbuf函數聲明如下:

extern int setvbuf(FILE * __restrict __stream, char *__restrict __buf, int __modes, size_t __n)

此函數第1個參數爲要操作的流對象;第2個參數buf指向一個長度爲第4個參數指示大小的緩衝區,第3個參數爲緩衝區類型


分別定義如下:

#define _IOFBF 0  //全緩衝
#define _IOLBF 1 //行緩衝
#define _IONBF 2 //無緩衝




#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
int main(void)
{
    FILE *fp;
    char msg1[] = "hello,world";
    char msg2[] = "hello\nworld";
    char buf[128];
    if((fp=fopen("no_buf1.txt", "w")) == NULL)
    {
        perror("file open failure!");
        return(-1);
    }
    setbuf(fp, NULL); //關閉緩衝區
    memset(buf, '\0', 128); //字符串buf初始化'\0'
    fwrite(msg1, 7, 1, fp); //向fp所指向的文件流中寫7個字符
    printf("test setbuf(no buf)!check no_buf1.txt\n");
    printf("now buf data is: buf=%s\n", buf); //因爲關閉了緩衝區,所以buf中無數據
    printf("press enter to continue!\n");
    getchar();
    fclose(fp);
    if((fp =fopen("no_buf2.txt", "w")) == NULL)
    {
        perror("file open failure!");
        return(-1);
    }
    setvbuf(fp, NULL, _IONBF, 0); //設置爲無緩衝模式
    memset(buf, '\0', 128);
    fwrite(msg1, 7, 1, fp);
    printf("test setvbuf(no buf)!check no_buf2.txt\n");
    printf("now buf data is :buf=%s\n", buf);
    printf("press enter to continue!\n");
    getchar();
    fclose(fp);
    if((fp=fopen("l_buf.txt", "w")) == NULL)
    {
        perror("file open failure!");
        return(-1);
    }
    /*
     * 設置爲行緩衝
     * 遇到'\n'就會刷新緩衝區
     * 所以後面buf中只顯示world字符,
     * 在調用fclose()之前,
     * 文件中寫入的內容爲"\n"之前的內容
     */
    setvbuf(fp, buf, _IOLBF, sizeof(buf));
    memset(buf, '\0', 128);
    fwrite(msg2, sizeof(msg2), 1, fp);
    printf("test setvbuf(line buf)!check 1_buf.txt, because line buf, only data before enter send to file\n");
    printf("now buf data is :buf=%s\n", buf);
    printf("press enter to continue!\n");
    getchar();
    fclose(fp);
    if((fp=fopen("f_buf.txt", "w")) == NULL)
    {
        perror("file open failure!");
        return(-1);
    }
    /*
     * 設置爲全緩衝模式
     * 會將msg2 <=128 字符的數據全部寫入緩衝區buf
     * 這時查看buf,裏面的內容是所有msg2的字符串的內容
     * 在調用fclose()之前,緩衝區的內容是不會刷新到文件中去的
     * 所以文件中的內容會爲空
     * 直到調用fclose()纔會把內容寫到文件中去
     */
    setvbuf(fp, buf, _IOFBF, sizeof(buf));
    memset(buf, '\0', 128);
    fwrite(msg2, sizeof(msg2), 1, fp);
    printf("test setbuf(full buf)!check f_buf.txt\n");
    printf("now buf data is: buf=%s\n", buf);
    printf("press enter to continue!\n");
    getchar();
    fclose(fp);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章