【问题标题】:C fwrite() writes amount of characters doubledC fwrite() 写入的字符量加倍
【发布时间】:2013-03-18 02:45:28
【问题描述】:

当我使用这段代码时

FILE *f = fopen(file, "wb");
fflush(f);
if (f==NULL) {
    //perror(f);
    return 0;
}
else{
    fwrite(text, sizeof(char), strlen(text), f);
    int i = fprintf(f, "%s", text);
    if (i>0) {
        fclose(f);

        return  1;
    }

(textconst char text[1024000],它被设置为函数中的参数之一) 如果我写

This is a test
This is a test

为了测试它是否可以写多行,它写了这个

This is a test
This is a testThis is a test
This is a test

为什么会出现这种奇怪的行为?

【问题讨论】:

    标签: c char fwrite


    【解决方案1】:

    你写了两次:

    fwrite(text, sizeof(char), strlen(text), f);
    int i = fprintf(f, "%s", text);
    

    选择一个

    【讨论】:

      【解决方案2】:

      这两行写了两次“文本”。他们做同样的事情。

      fwrite(text, sizeof(char), strlen(text), f);
      int i = fprintf(f, "%s", text);
      

      唯一的区别是 fprintf 比 fwrite 多写一个字节 '\0'。

      【讨论】:

      • 哈,比你快 12 秒 ;)
      猜你喜欢
      • 2023-01-10
      • 2020-08-23
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 2021-05-14
      • 2023-03-03
      相关资源
      最近更新 更多