曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3815|回复: 0
打印 上一主题 下一主题

fwrite

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-2-10 12:16:42 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
 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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-7 05:20 , Processed in 0.076464 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表