|
地板

楼主 |
发表于 2009-7-14 01:43:59
|
只看该作者
通过调试说明写文件的实质以及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() 至少在默认情况下是不支持中文的,故而不能在打印的字符串中含有中文,否则会看到乱码。 |
|