【问题标题】:Extra character at end while copying?复制时末尾有多余的字符?
【发布时间】:2015-07-25 19:01:17
【问题描述】:

这让我发疯了我正在尝试制作一个简单的程序来使用以下代码复制任何类型的文件,但我得到的结果是出乎意料的(复制文件末尾的一两个额外字符?)。例如,如果我的原始文件包含This is an example,则复制的文件包含This is an exampleÿ

代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp,*fpp;
    char pbuff, fname[32];
    int i;

    printf(" FILE NAME TO OPEN : ");
    scanf(" %32s", fname);
    fp = fopen(fname, "rb");
    fpp = fopen("file", "wb");
    if(fp==NULL)
    {
        printf("NO SUCH FILE. EXITING NOW.");
        getch();
        exit(1);
    }

    while(!feof(fp))
    {
        pbuff = fgetc(fp);
        fputc(pbuff, fpp);
    }

    printf("SUCCESSFULLY CREATED!");
    fclose(fp);
    fclose(fpp);
    getch();
    return(0);
}

谁能帮我解决这个问题?我会非常感激的。

【问题讨论】:

  • feof() 在 while 循环中会产生问题,不要使用它,使用 fgets()。
  • 你能说得更具体点吗?
  • 是的 'while(!feof(fp))' 来自标题 :(
  • 0) " %32s" --> " %31s" 1) int ch;while(EOF!=(ch = fgetc(fp)))fputc(ch, fpp);

标签: c copying


【解决方案1】:

原因是feof(与大多数语言/环境中的大多数文件结束指示符一样)仅在达到文件结束后才设置。由于您写了字符然后才检查 EOF 状态,因此您写了 1 太多字符。如果在调用期间到达文件末尾,fgetc 的返回值是一个预定义的 EOF。

您可以通过 2 种方式中的一种来解决这个问题:

while(true)
{
    pbuff = fgetc(fp);
    if(feof(fp))
         break;
    fputc(pbuff, fpp);
}

或者:(编辑为 melpomene 正确注意!)

// Change pbuff to type int in the declartion, and then...
while(true)
{
    pbuff = fgetc(fp);
    if(EOF == pbuff)
         break;
    fputc(pbuff, fpp);
}

【讨论】:

  • pbuff 不能是 char。它必须是int
  • 我可以给你买啤酒! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 2019-09-09
  • 2016-12-22
  • 1970-01-01
相关资源
最近更新 更多