Group
File Management in C++
Objective
1. Ask the user to enter the names of the source and destination files.
2. Open the source file using `ifstream` for reading.
3. Open the destination file using `ofstream` for writing.
4. Read each line from the source file and write it into the destination file.
5. Close both files and confirm that the content has been copied successfully.
Develop a program that copies the contents of one file to another.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for input and output stream
#include <fstream> // Include for file handling
#include <string> // Include for using the string class
using namespace std;
int main() {
string sourceFile, destinationFile; // Variables to store filenames
// Ask user for source and destination file names
cout << "Enter the source file name: ";
cin >> sourceFile;
cout << "Enter the destination file name: ";
cin >> destinationFile;
ifstream inFile(sourceFile); // Open the source file for reading
ofstream outFile(destinationFile); // Open the destination file for writing
// Check if the source file opened successfully
if (!inFile) {
cout << "Error: Could not open the source file." << endl;
return 1; // Exit with error code
}
// Check if the destination file opened successfully
if (!outFile) {
cout << "Error: Could not open/create the destination file." << endl;
return 1; // Exit with error code
}
string line; // Variable to hold each line read from the source file
// Read and copy lines from source to destination
while (getline(inFile, line)) {
outFile << line << endl; // Write the line to the destination file
}
// Close both files
inFile.close();
outFile.close();
// Confirm successful copy
cout << "File copied successfully from " << sourceFile << " to " << destinationFile << "." << endl;
return 0; // End of program
}
Output
Enter the source file name: original.txt
Enter the destination file name: copy.txt
File copied successfully from original.txt to copy.txt.