免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1142 | 回复: 2
打印 上一主题 下一主题

请教高手一个文件读写的问题! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-07-23 02:34 |只看该作者 |倒序浏览
我最近写了这么一个函数,通过结构体地址将其数据存入文件:

int save_one_userinfo(struct user *user_pt, int offset)
{
        FILE *fp;

        if (!(fp = fopen("userinfo", "wb")))
        {
                printf("Fail to open file!\n");
                return 0;
        }
        fseek(fp, offset*sizeof(struct user), SEEK_SET);
        fwrite(user_pt, sizeof(struct user), 1, fp);
        fclose(fp);

        return 1;
}

但实际操作后发现他以wb方式打开文件再写入时数据全被清空只留下写下的那一块
打开方式改成a后他又是以文件尾为开头计算offset量的
请教各位要在已有文件中从文件头根据offset在随机位置存入一块数据而不致于清空文件该如何实现?谢谢!

论坛徽章:
0
2 [报告]
发表于 2006-07-23 09:42 |只看该作者
打开方式用 "rb+" 就可以了。

别使用"a" or "w".


               
                    r or rb             open file for reading

                    w or wb             truncate to zero length or create
                                         file for writing

                    a or ab             append; open file for writing at
                                         end of file, or create file or
                                         writing

                    r+, rb+, or r+b     open file for update (reading and
                                         writing)

                    w+, wb+, or w+b     truncate file to zero length or
                                         create file for update

                    a+, ab+, or a+b     append; open or create file for
                                         update at end-of-file
      When a file is opened for append (i.e., when type is a, a+, ab+, or
      a+b), it is impossible to overwrite information already in the file.
      All output is written at the end of the file, regardless of
      intervening calls to fseek().  

[ 本帖最后由 zhhui2000 于 2006-7-23 09:45 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2006-07-23 10:52 |只看该作者
问题已经解决。谢谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP