Hello everyone. First time poster here.
I'm writing 2 functions that will copy a file. The first version of my function seems to work without any problem. I say seems to as I haven't yet run any kind of diff command to test to see if the files are actually different. I'm doing this on DOS 6.22, believe it or not, so I don't have access to a diff command.
The first version is based on some code I found online that uses fgets to copy the file line by line. I think this will only work for text files, is that correct?
Code:
int copyFile(char sFile[256], char tFile[256]) {
char line[128];
FILE *sourceFile;
FILE *targetFile;
if (fileExists(sFile) && fileExists(tFile)) {
sourceFile = fopen(sFile,"r");
targetFile = fopen(tFile,"w");
while (fgets(line,sizeof line,sourceFile) != NULL) {
fputs(line,targetFile);
}
fclose(sourceFile);
fclose(targetFile);
} else {
return(1);
}
return(0);
}
I'm able to call this function as follows:
Code:
copyFile("FILEA.TXT","FILEB.TXT")
...and it works. And near as I can tell, there are no differences in the file. However, I'm wanting to figure out this other version of the function which copies 1 character at a time. If I understand this correctly, copying 1 character at a time is better?
My second version of the function works, except that it always puts an extra character at the end of the file. At first I didn't even notice the extra character as it seems to be invisible. However, when I used my function to copy the copy program I was working on, the copied version wouldn't compile because the compiler was catching the extra character.
The second version of the function is based on the code I found here C program to copy files | Programming Simplified and here C program to copy contents of one file to another file - GeeksforGeeks.
Code:
int copyFile(char sFile[256], char tFile[256]) {
FILE *sourceFile;
FILE *targetFile;
char c;
sourceFile = fopen(sFile, "r");
if (sourceFile == NULL) {
printf("Source file doesn't exist.\n");
return(1);
}
targetFile = fopen(tFile, "r");
if (targetFile != NULL) {
printf("Target already exists. ABORT!\n");
return(1);
}
fclose(targetFile);
targetFile = fopen(tFile, "w");
if (targetFile == NULL) {
printf("Can't open file for writing! Permission error?\n");
return(1);
}
do {
c = fgetc(sourceFile);
fputc(c, targetFile);
} while (c != EOF);
fclose(sourceFile);
fclose(targetFile);
return(0);
}
To summarize, my questions are:
- Is the line by line copy program limited to text files only?
- Is the character copy version better? If so, how?
- Why is the character copy implementation including extra characters at the end of the file?
Thanks everyone.