C++ File handling: Copy contents from one text file to another
5. Copy Contents of One Text File to Another
Write a C++ program to copy the contents of one text file to another.
Sample Solution:
C Code:
Sample Output:
File copied successfully
Explanation:
In the above exercise,
- Use the std::ifstream class to open the input file and the std::ofstream class to create or overwrite the output file.
- Check if both files were successfully opened using the is_open() function.
- If both files are open, use a while loop and std::getline() to read each line from the input file.
- Write each line to the output file using the output stream operator <<.
- After the loop ends, close both files using inputFile.close() and outputFile.close().
- Finally, display a message indicating that the file was copied successfully
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to open a source file and copy its content to a destination file using file streams.
- Write a C++ program that reads from one file and writes each line to a new file, ensuring that the copy is exact.
- Write a C++ program to implement file copying by reading the source file character by character and writing to the target file.
- Write a C++ program to copy a text file to another file and confirm the copy by comparing the file sizes.
CPP Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Count number of words in a text file.
Next C++ Exercise: Find and replace specific word in text file.
What is the difficulty level of this exercise?