Copying a file C program example using the C file input/output functions



Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro with SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Copying a file C program example using the C file input/output functions

To show: How to use the C file I/O functions to copy a file




// Copying a file program example

#include <stdio.h>

// function prototype

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


void main(void)


char source[80], destination[80];

// get the source and destination names

printf("\nEnter source file: ");

gets_s(source, 80);

printf("\nEnter destination file: ");

gets_s(destination, 80);

if(file_copy(source, destination) == 0)

puts("Copy operation successful");


fprintf(stderr, "Error during copy operation");


int file_copy(char *oldname, char *newname)


FILE *fold, *fnew;

errno_t err = 0, err1 = 0;

int c;


// Open the source file for reading in binary mode

// fopen(oldname, "rb"), using a secure version

err = fopen_s(&fold, oldname, "rb");

err1 = fopen_s(&fnew, newname, "wb" );


if(err != 0)

return -1;

// Open the destination file for writing in binary mode

if(err1 != 0)



return -1;


// Read one byte at a time from the source, if end of file has not been reached, write the byte to the destination



c = fgetc(fold);


fputc(c, fnew);






return 0;



Output example:


Enter source file: C:\newsix.txt

Enter destination file: C:\newsixcopy.txt

Copy operation successful

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index