-1

This is making me nuts I am trying to make a simple program to copy any type of file using the following code but the result I get is unexpected (one or two extra characters at the end of copied file?). For instance if my original file has This is an example the copied file contains This is an exampleÿ

CODE

#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);
}

Can anyone help me out with this one? I will be really very thankful.

Naveen
  • 105
  • 1
  • 9

1 Answers1

2

The reason is that feof (like most end-of-file indicators in most languages/environments) is only set AFTER the end-of-file has been reached. Since you write the character and only then check the EOF status, you're writing 1 too many characters. fgetc's return value is a predefined EOF if the end-of-file was reached during the call.

You could solve that in 1 of 2 ways:

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

Or: (edit as melpomene correctly noticed!)

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