Friday, July 20, 2012

Simple File Copy Algorithm in ANSI C

The simplest implementation for creating a copy of a file is to copy the original file character by character into the new file.

Against all my expectations, I managed to create a copy of a 365 Mb file in under 40 seconds on my on my modest laptop running Ubuntu 12.04.

The program takes as arguments the path to the source file (first argument) and the path to the destination file (second argument).
#include<stdio.h>

/*The number of arguments that the program takes*/
#define ARG_NUMBER            3
/*The argument index for the source file path*/
#define SOURCE_ARG_INDEX      1
/*The argument index for the destination file path*/
#define DESTINATION_ARG_INDEX 2

/*Description:
 * The program does copies a file to another.It receives as arguments
 * the path to the source file and the path to the destination file.
 */
int main(int argc, char** argv)
{
    FILE *sourceStream = NULL, *destinationStream = NULL;
    char c;
    /*Verifies if the program received a correct number of arguments*/
    if (argc == ARG_NUMBER)
    {
        /*Opens a stream to the source file*/
        sourceStream = fopen(argv[SOURCE_ARG_INDEX], "rt");
        /*Checks if the stream was successfully established*/
        if (sourceStream != NULL)
        {
            /*Opens a stream to the destination file*/
            destinationStream = fopen(argv[DESTINATION_ARG_INDEX], "wt");
            /*Checks if the stream was successfully established*/
            if (destinationStream != NULL)
            {
                /*Copies the source file into the destionation file*/
                while (feof(sourceStream) == 0)
                {
                    c = fgetc(sourceStream);
                    fputc(c, destinationStream);
                }
                /*Closes the streams*/
                fclose(sourceStream);
                fclose(destinationStream);
            }
            else
            {
                perror("Could not open destination file.");
            }
        }
        else
        {
            perror("Could not open source file.");
        }
    }
    else
    {
        perror("Incorrect number of arguments. You should provide the "
                "path to the sourceStream file and the destinationStream file");
    }
    return 0;
}

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger