Small Issue with File Copy Program in C

aceman817

Senior member
Jul 15, 2001
204
0
0
I wrote a small program using C to copy the contents of one file into another. The problem is that it also copies an extra chracter at the end. The character is "ÿ". Any ideas on how I can solve this? I just want to have a simple program for file copy using stdio.h. Here is the code:

#include <stdio.h>

int main() {
FILE * inFile, * outFile;
inFile = fopen("c:\\in_test.txt","r");
outFile = fopen("c:\\out_test.txt","w");

// Copy each character from source
// till destination until end of file
while (!feof(inFile))
fputc(fgetc(inFile), outFile);

// Close files and return
fclose(outFile);
fclose(inFile);
return 0;
}
 

Cerebus451

Golden Member
Nov 30, 2000
1,425
0
76
When you read the last character of the file, the EOF flag is not yet set, so feof would return false. That means you are going into the loop one extra time. This last time, fgetc does not return a valid character, it just sets the EOF flag for the file (and returns the integer constant EOF), so fputc ends up writing an extra character.
 

aceman817

Senior member
Jul 15, 2001
204
0
0
Thanks for the quick reply. I am trying to figure out a way for the loop to execute EOF-1 times but cannot come up with a simple method of doing it. Is there a way I can change the loop?
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Two options:

One - determine the file length and test a counter;

Second:
Test for error return from the read - not the EOF.
 

aceman817

Senior member
Jul 15, 2001
204
0
0
Ok. I'd prefer not to use a counter as that would make the program slower. Is there a relatively simple way to test for the error?
 

aceman817

Senior member
Jul 15, 2001
204
0
0
I modified the program as follows and it seems to work. I am now using a test character. It seems a little unconventional though, so if you have any ideas on how to do it "properly", please let me know.

#include <stdio.h>

int main() {
FILE * inFile, * outFile;
inFile = fopen("c:\\in_test.txt","r");
outFile = fopen("c:\\out_test.txt","w");
char c;

// Copy each character from source
// till destination until end of file
while (!feof(inFile)) {
c = fgetc(inFile);
if(c != 'ÿ')
fputc(c, outFile);
}

// Close files and return
fclose(outFile);
fclose(inFile);
return 0;
}
 

singh

Golden Member
Jul 5, 2001
1,449
0
0
1. Note that fgetc() returns an int not a char and the return value can be used to check for eof.
2. Modified program below

int main()
{
FILE* inFile = 0;
FILE* outFile = 0;
inFile = fopen("f:\\in.txt","r");
outFile = fopen("f:\\out.txt","w");

if(!inFile || !outFile)
return 1;

int c = -1;
while((c = fgetc(inFile)) != EOF)
fputc(c, outFile);

fclose(outFile);
fclose(inFile);
return 0;
}