免费注册 查看新帖 |

Chinaunix

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

大侠:c语言修改文件出错,求解! [复制链接]

论坛徽章:
3
天蝎座
日期:2014-10-25 13:44:312015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:48:31
1 [报告]
发表于 2009-01-10 22:23 |显示全部楼层
无聊,把代码格式化了一下,一下子就看到一个BUG了




#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define txtfile "test"
int main()
{
        FILE *fp, *fp2; char tmp[200];char *line; size_t len; int ret;

        //read content form txtfile;
        fp=fopen(txtfile,"r");
        if(fp == NULL)
       {
              perror(txtfile);
              exit(EXIT_FAILURE);
       }


        while ((read = getline(&line, &len, fp)) != -1)
        {
                if(line=="\n")
                {
                       continue;
                }

                if(strstr(line,"name=apple"))
                {
                        strcat(tmp,"name=banana");
                }
                else
                {
                        strcat(tmp,line);
                }

                strcat(tmp,"\n");
        }
        fclose(fp);

        //write content from tmp back to txtfile;
        fp2 = fopen(txtfile, "w");
        if(fp == NULL)——fp2???
        {
               perror(txtfile);
               exit(EXIT_FAILURE);
        }

        ret=fputs(tmp,fp);
        if(ret <0||ret==EOF)
        {
                printf("Write error!\n");
        }

        fclose(fp2);

        return 0;
}

论坛徽章:
3
天蝎座
日期:2014-10-25 13:44:312015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:48:31
2 [报告]
发表于 2009-01-10 22:24 |显示全部楼层
另外
局部变量未初始化,比如tmp[200]。


看程序的要求,以及代码的风格,估计楼主还是学生吧;

嗯,一点小建议,代码写完了,不用立即就编译,立即就运行,先看看代码是不是有明显的BUG;

[ 本帖最后由 ilex 于 2009-1-10 22:25 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP