Skip to content

Instantly share code, notes, and snippets.

@mohamad-wael
Created May 6, 2021 16:04
Show Gist options
  • Save mohamad-wael/bcff6f5023d1c96c08ebc2af1f569106 to your computer and use it in GitHub Desktop.
Save mohamad-wael/bcff6f5023d1c96c08ebc2af1f569106 to your computer and use it in GitHub Desktop.
How to copy a file character by character in C ?
#include <stdio.h>
#include <stdlib.h>
/* Copy a file one character at a time .*/
int
main
(int argc , char * argv [ ] ){
if (argc != 3 ){
printf ("%s\n" , "Usage: fgp fom to" );
exit (EXIT_FAILURE ); }
char *fromPath , *toPath;
fromPath = argv [1 ];
toPath = argv [2 ];
FILE *from = fopen (fromPath , "r" );
if (!from ){
perror (fromPath );
exit (EXIT_FAILURE ); }
FILE *to = fopen (toPath , "a" );
if (!to ){
perror (toPath );
if(fclose (from ) != 0 )
perror (fromPath );
exit (EXIT_FAILURE ); }
char c;
while (((c = getc (from ) ) != EOF )
&&
(putc (c , to ) != EOF ));
if (ferror (from ) )
perror (fromPath );
if (ferror (to ) )
perror (toPath );
if (fclose (from ) != 0 )
perror (fromPath );
if (fclose (to ) != 0 )
perror (toPath ); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment