曲径通幽论坛

标题: fflush [打印本页]

作者: beyes    时间: 2009-2-10 14:23
标题: fflush
fflush 库函数清除文件缓冲区,使所有在文件流里的数据的都被马上写--你可以使用它来确保这种情况。例如,在试图读取一个应答前,一个交互式的提示就已经送到了终端。在继续下去之前,确定重要数据已经提交到磁盘这非常重要。有时,当你在调试程序时,要确保程序正在写数据而不是挂起,你就需要使用它。注意,一个隐式的 flush操作在 fclose调用时发生(即调用 fclose时也会产生 flush缓冲区的行为),所以你不必在 fclose之前再调用 fflush .

使用方法
#include <stdio.h>
int fflush(FILE *stream);

作者: beyes    时间: 2009-3-15 17:09
标题: fflush 测试程序段
#include <stdio.h>

int main(void)
{
        int i;
        fputs("please input an integer", stdout);
        scanf("%d", &i);
        fflush(stdin);
        printf("%d\\n", i);

        return 0;
}
作者: beyes    时间: 2009-3-15 21:40
标题: fflush man内容
man 手册页说明
DESCRIPTION
       The  function  fflush()  forces a write of all user-space buffered data
       for the given output or update stream via the stream’s underlying write
       function.  The open status of the stream is unaffected.
fflush() 函数通过流的底层写函数,强制把用户空间缓冲区数据写到给定的输出流或更新流中。流的打开状态不受影响。
作者: beyes    时间: 2009-7-14 01:43
标题: 通过调试说明写文件的实质以及fflush()函数的应用
先来看一个普通的写文件程序
#include <stdio.h>
#include <ncurses.h>
#include <string.h>

int main(void)
{
    FILE *stream;
    char msg[] = "This is a test";
   
    stream = fopen("test2.txt", "w+");
    fwrite(msg, strlen(msg), 1, stream);
    return 0;
}
编译生成可执行文件后,用 GDB 进行调试。在 return 0; 语句处下断,然后 r 运行到断点处,先不急于退出。在另外一个窗口用 cat test2.txt 命令,结果发现 test2.txt 在经过 fwrite() 函数后文件中仍然没有内容。而只有当程序结束时,再调用 cat 查看时,文件中才会被填写了内容,因此可以知道,在程序退出时,写往文件中的内容仍然是在用户缓冲区中的。

再看用了 fflush() 函数文件
#include <stdio.h>
#include <ncurses.h>
#include <string.h>

int main(void)
{
    FILE *stream;
    char msg[] = "This is a test";
   
    initscr();
    stream = fopen("test.txt", "w+");
    fwrite(msg, strlen(msg), 1, stream);
    printw("%s\\n","press any key to flush the content to file");
    getch();
    fflush(stream);
    printw("%s\\n","press any key to quit");
    getch();
    endwin();

    return 0;
}
在上面程序中,在 printw("%s\\n","press any key to quit"); 函数这里下断,当程序运行到此断点处时,像上面同样用 cat 查看 test.txt中的内容,发现文件中已经有了 msg的信息。由此可见,用户缓冲区在 fflush()后已经被清空,原来的内容已被写往其参数指定的流中,这个流可以是标准输出流,也可以是打开了的文件流。

另外,这个程序中使用了 curses 库中的 getch() 函数。在使用 curses 库的程序,应该先以 initscr() 开始,并以 endwin() 结束。如果在 initscr() 和 endwin() 中间使用 printf() 这样的打印函数,已经看不到任何打印内容,这是因为程序已经进入到 curses 空间中。所以这里使用 printw() 函数来打印内容,但 printw() 至少在默认情况下是不支持中文的,故而不能在打印的字符串中含有中文,否则会看到乱码。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2