Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C Program to Copy Files

    C Programming Examples


    This C program is used to copy a file.

    Firstly you will specify the file to copy and then you will enter the name of target file, You will have to mention the extension of file also. We will open the file that we wish to copy in read mode and target file in write mode.

    Example:

    #include<stdio.h>    
    #include<stdlib.h>
        
        int main()
        {    
        char ch, source_file[25], target_file[25];
        
        FILE *source, *target;    
        
        printf("Enter name of file to copy\n");
        gets(source_file);    
        
        source = fopen(source_file, "r");
        
            if( source == NULL )
            {
                printf("Press any key to exit...\n");
                exit(EXIT_FAILURE);
            }
        
        printf("Enter name of target file\n");
        
        gets(target_file);
        
        target = fopen(target_file, "w");
        
        if( target == NULL )
        {
            fclose(source);        
            printf("Press any key to exit...\n");        
            exit(EXIT_FAILURE);
        }    
        
        while( ( ch = fgetc(source) ) != EOF )
            fputc(ch, target);
            
            printf("File copied successfully.\n");        
            fclose(source);        
            fclose(target);
            
            return 0;
    }

    Program Output:

    copy-file-c



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.