Solution for Exercise 23-7

ex2307

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *original,*copy;
    int c;

    original=fopen("ex2307.c","r");
    copy=fopen("ex2307.bak","w");
    if( !original || !copy)
    {
        puts("File error!");
        exit(1);
    }
    while( (c=fgetc(original)) != EOF)
        fputc(c,copy);
    puts("File duplicated");
    return(0);
}

Output

File duplicated

Notes

* Line 9 assumes that this source code file is named ex2307.c. If not, edit that line to reflect the proper source code filename. You might also want to change Line 10, if you like.

* The if statement at Line 11 uses a the logical OR to test both file pointers in one sentence. Of course, an error specific to each file would be better.

* You may delete the duplicate file, ex2307.bak, if you like.