You can't find the utility function for copying a file because there isn't a need for it in the same way; it can be built out of 'spare parts'. Functions like unlink()
and symlink()
can't be built in terms of other functions, whereas functions such as a hypothetical copy_file()
can (so you must).
Given two open file streams, f1
for reading and f2
for writing, then you could use:
void fcopy(FILE *f1, FILE *f2)
{
char buffer[BUFSIZ];
size_t n;
while ((n = fread(buffer, sizeof(char), sizeof(buffer), f1)) > 0)
{
if (fwrite(buffer, sizeof(char), n, f2) != n)
err_syserr("write failed\n");
}
}
The err_syserr()
function is for error reporting including the string passed as an argument and the error message implied by errno
*; it does not return. BUFSIZ
is defined in <stdio.h>
but you might choose to use a bigger value. You might prefer not to error report like that, but have the function return 0 on success and -1 on any failure.
int fcopy(FILE *f1, FILE *f2)
{
char buffer[BUFSIZ];
size_t n;
while ((n = fread(buffer, sizeof(char), sizeof(buffer), f1)) > 0)
{
if (fwrite(buffer, sizeof(char), n, f2) != n)
return -1;
}
return 0;
}
Note that because the function does not open the files, it does not close them either. This means you could use it to concatenate multiple input files to a single output file, for example. You could use a wrapper function to open a file for reading and another for writing.
* Actually, err_syserr()
is a function like printf()
which takes a format string and other arguments, and then reports the error message as described and exits.