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.
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.txt
and append it to the file copy.txt
. We will repeat this process till we rich the end of the original.txt
file.
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.txt
file to the file copy.txt
we will close both files.
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
.
Line 10: We open the file original.txt
in read mode specified by the second argument r
.
Line 13: We open the file copy.txt
in write mode specified by the second argument w
.
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 function fputc()
.
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