|
fwrite 和 fread 相似。它从数据缓冲区取出数据记录并写到输出流(output stream)。函数成功时返回已写的数据记录条数。用法:
#include <stdio.h>
size_t fwrite (const void *ptr, size_t size, size_t nitems, FILE *stream);
fread 和 fwrite 不建议在结构体中使用。因为用 fwrite 来写,在不同的机器架构里会带来潜在的移植问题。
*ptr : 从这个指针所指的地方取得要写入的数据;
size : 一次要写入的数据长度;
nitems : 一次要写入多少个 size 的数据;
stream : 写到 stream 文件流所指向的文件中;
注意:如果缓冲区中的数据最大也只有 size ,那么就不能定义 nitems 为 2,这样的情况一般是一次性全部写入,所以 nitems 为 1
测试代码:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
//void flush(FILE *stream);
int main(void)
{
char msg[] = "This is a test";
FILE *stream;
stream = fopen("DUMMY.FIL", "w");
fwrite(msg, strlen(msg), 1, stream);
fwrite(msg, strlen(msg), 1, stream);
return 0;
}
运行及输出:[root@localhost C]# ./fflush.exe
[root@localhost C]# cat DUMMY.FIL
This is a testThis is a test[root@localhost C]#
如果改成以下代码:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
//void flush(FILE *stream);
int main(void)
{
char msg[] = "This is a test";
FILE *stream;
stream = fopen("DUMMY.FIL", "w");
fwrite(msg, strlen(msg), 2, stream); /*有错*/
return 0;
}
那么执行后:
[quote][root@localhost C]# cat DUMMY.FIL
This is a tes |
|