How to copy a file character-by-character in C
C is a general-purpose programming language that was developed in the 1970s. It is a compiler-based language; hence it uses C compilers to convert C code to machine instructions to be run on the CPU. It is commonly used to create programs that require low-level access to underlying system hardware.
In this Answer, we will discuss the character-by-character file copying method, in which we iterate over all the characters in the existing source file, one at a time, and add them to the destination file.
Algorithm
Below are the steps required to copy character-by-character data from one file to another.
We need to open the file from where we want to copy data. Let's call this file
original.txt.Now, we need to create and open a new file that will be used to store the data that it retrieves from the original file. We can call this file
copy.txt.
Note: To open files in C we can use the function fopen().
Once we have opened both files, we will read each character from the file
original.txtand append it to the filecopy.txt. We will repeat this process till we rich the end of theoriginal.txtfile.
Note: To read data from a file, we can use the fgetc() function. To write data to a file, we can use the fputc() function.
Once we have copied all data from the
original.txtfile to the filecopy.txtwe will close both files.
Code application
Below, we can see a C application that shows how to implement the character-by-character copy approach to create a copy of the file named orignial.txt.
Code explanation
Line 10: We open the file
original.txtin read mode specified by the second argumentr.Line 13: We open the file
copy.txtin write mode specified by the second argumentw.Line 16: We get the first character from the source file using the function
fgetc()to check if it is empty.Lines 18–23: We run a loop till we have not run out of characters to read in the source file
original.txt. For every character we read, we append it to the target file using the functionfputc().Lines 26–27: After we have copied the files, we close both files using the
fclose()function and display a message that prompts the user that the file was successfully copied.
Free Resources