Copying a file. - C File

C examples for File:File Operation

Description

Copying a file.

Demo Code

#include <stdio.h>

int file_copy( char *oldname, char *newname );

int main( void )
{
    char source[80], destination[80];
    printf("\nEnter source file: ");
    gets_s(source);//from  w ww.  jav a  2 s.c  o  m
    printf("\nEnter destination file: ");
    gets_s(destination);

    if ( file_copy( source, destination ) == 0 )
        puts("Copy operation successful");
    else
        fprintf(stderr, "Error during copy operation");
    return(0);
}
int file_copy( char *oldname, char *newname )
{
    FILE *fold, *fnew;
    int c;

    /* Open the source file for reading in binary mode. */

    if ( ( fold = fopen( oldname, "rb" ) ) == NULL )
        return -1;

    /* Open the destination file for writing in binary mode. */

    if ( ( fnew = fopen( newname, "wb" ) ) == NULL  )
    {
        fclose ( fold );
        return -1;
    }

    while (1)
    {
        c = fgetc( fold );

        if ( !feof( fold ) )
            fputc( c, fnew );
        else
            break;
    }

    fclose ( fnew );
    fclose ( fold );

    return 0;
}

Result


Related Tutorials