copying a file
-
Can someone tell me if this code works to copy a binary file?
while ((ch = fgetc(source)) != EOF) {
fputc(ch, target);
}What if the file contains a byte that is 255? Won't it get converted to -1 and break the loop? Thank you.
Depends on declaration of
ch
. If it’s anint
(as it should), all is fine as255 != -1
. If it’schar
, it fails, with or without compiler warnings.Mircea
-
Can someone tell me if this code works to copy a binary file?
while ((ch = fgetc(source)) != EOF) {
fputc(ch, target);
}What if the file contains a byte that is 255? Won't it get converted to -1 and break the loop? Thank you.
You should not use fgetc, fgets, or any other character based function to process binary files. You should use fread | Microsoft Learn[^] and fwrite | Microsoft Learn[^].
-
Can someone tell me if this code works to copy a binary file?
while ((ch = fgetc(source)) != EOF) {
fputc(ch, target);
}What if the file contains a byte that is 255? Won't it get converted to -1 and break the loop? Thank you.
While your method may work, assuming that
ch
is an int, and so does not have the 255/-1 issue, your method is horribly inefficient. Richard's suggestion to use fread/fwrite produces much better performance. For example, given an 8M file, looping through your code 100 times took about 32 seconds. Using a fread/fwrite using a 4K buffer, the same 100 lops took just under 1 second to complete. This was on a PI-3, and successive runs remained stable. I'd expect an 8M file to sit comfortably in the file cache, so the difference is totally down to the difference between extracting a single char at a time, and reading a lot of characters at a time."A little song, a little dance, a little seltzer down your pants" Chuckles the clown