Write a program to copy the content of one file into another.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char **argv) {

    const char * fn1 = "output.bin";
    const char * fn2 = "integer_file";
    const static int maxString = 1024;	// read buffer size
    FILE *fh1, *fh2;

    fh1 = fopen(fn1, "r");
    fh2 = fopen(fn2, "wb");

    char buf[maxString];
	char * rc;
    while(( rc = fgets(buf, maxString, fh1) )) {  // Reads a line and put in a buffer
		fputs(buf, fh2);
    printf("File content copied\n");

    return 0;

When you compile and execute the above program it produces the following result on Linux:

File content copied

Brief Explanation

  • The program starts by opening file fn1 for reading and file fn2 in binary mode for writing.
  • Using a while loop and fgets function, a line is read at time from the first file and written into the second file using function fputs.
  • Once the content has been copied, both files are closed using the function fclose.

Add comment

Security code