I made a code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char * argv[]) // taking files
{
FILE * fp;
FILE * fp2;
int c;
.
. // checking possible problems
.
while ( (c = fgetc(fp)) != EOF){ // copying one file to another one
fputc (c, stdout);
fputc (c, fp2);
}
fclose(fp);
fclose(fp2);
fp = NULL;
fp2 = NULL;
return EXIT_SUCCESS;
}
I would ask you, if is it possible to make the same while statement with use of fgets
function instead of fgetc
- like:
fgets(fp, sizeof(fp), stdin));
Yes, it's possible to use fgets()
and fputs()
.
If you're using POSIX systems, you might find getline()
better than fgets()
, but you'd still use fputs()
with it. Or you might find fread()
and fwrite()
appropriate instead. All of those work on arrays — you get to choose the size, you'd likely be using 4096 bytes as a buffer size.
For example:
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp) != NULL)
{
fputs(buffer, stdout);
fputs(buffer, fp2);
}
Or:
char buffer[4096];
size_t nbytes;
while ((nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp)) > 0)
{
fwrite(buffer, sizeof(char), nbytes, stdout);
fwrite(buffer, sizeof(char), nbytes, fp2);
}
Warning: uncompiled code.
Note that in theory you should test that the fwrite()
operations worked OK (no short writes). Production quality code would do that. You should also check that the fputs()
operations succeed too.
Note that as hinted at by user2357112, the original code will work with arbitrary binary files (containing null bytes '\0'
) quite happily (though stdout
may be less happy with it). Using fread()
and fwrite()
will work perfectly with binary files, and the only issue with text files is that they'd ignore newlines and write blocks of text as they're read (which is not usually an actual problem).