Copying the contents of one file to another in C involves reading data from the source file and writing it to the destination file. This process is useful for file management tasks, such as creating backups or duplicating data.
Program: Copy Contents of One File to Another in C
Here’s a simple program that demonstrates how to copy the contents from one file to another.
Explanation of the Program
Header Files:
#include <stdio.h>
: Includes standard I/O functions for file handling.#include <stdlib.h>
: Provides definitions for exit status and error handling.
File Pointers:
FILE *sourceFile, *destFile;
: Declares pointers to handle the source and destination files.
Open Source File:
- Opening:
This line attempts to open
source.txt
in read mode. - Error Checking:
If the file can't be opened (e.g., it doesn't exist), an error message is displayed and the program exits.
- Opening:
Open Destination File:
- Opening:
This opens (or creates)
destination.txt
in write mode. - Error Checking: Similar to the source file, it checks for errors when opening the destination file.
- Opening:
Copying Process:
- The program uses a loop to read characters from the source file one at a time:
fgetc(sourceFile)
reads a single character fromsourceFile
.- The loop continues until the end of the file (
EOF
) is reached. fputc(ch, destFile)
writes the read character todestFile
.
- The program uses a loop to read characters from the source file one at a time:
Closing Files:
- After copying is complete, both files are closed:
- This ensures that all resources are properly released.
- After copying is complete, both files are closed:
Program Output:
- After the successful completion of the file copy operation, a message is printed:
- After the successful completion of the file copy operation, a message is printed:
How to Run the Program
Create the Source File: First, create a text file named
source.txt
in the same directory as the program and add some text to it.Compile the Code: Use a C compiler like
gcc
to compile the code:Execute the Program: Run the compiled program:
Example Output
Assuming source.txt
contains the following text:
After running the program, the output will be:
The contents of destination.txt
will now be:
Conclusion
This program illustrates the basic file handling operations in C: opening files, reading from a source file, writing to a destination file, and closing the files afterward. Understanding how to work with files is a foundational skill in C programming, enabling you to manage data effectively and efficiently. This method can be expanded for more complex file operations, such as error logging, binary file copying, or even merging multiple files.