Assignment: File Handling using Constructors in C++
Objective:
To demonstrate how file reading and writing can be implemented in C++ using constructors with separate
classes for each operation.
Key Points:
- Uses two classes: FileWriter and FileReader.
- Each class contains a constructor to execute its specific task.
- Demonstrates good practice of separating responsibilities in object-oriented programming.
- File handling is done using <fstream> in C++.
Main Idea:
Each class is responsible for a single task: FileWriter writes data to a file, while FileReader reads data from a
file.
Conclusion:
The separate way offers better organization and code modularity, which is useful in larger projects.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Class for writing to a file
class FileWriter {
public:
FileWriter(const string& filename, const string& content) {
ofstream outfile(filename);
if (outfile.is_open()) {
outfile << content;
cout << "Content written successfully.\n";
outfile.close();
} else {
cout << "Unable to open file for writing.\n";
};
// Class for reading from a file
class FileReader {
public:
FileReader(const string& filename) {
ifstream infile(filename);
string line;
if (infile.is_open()) {
cout << "Reading from file:\n";
while (getline(infile, line)) {
cout << line << endl;
infile.close();
} else {
cout << "Unable to open file for reading.\n";
}
};
int main() {
FileWriter writer("sample.txt", "Hello from constructor-based file writer!");
FileReader reader("sample.txt");
return 0;
Outcome:
Content written successfully.
Reading from file:
Hello from constructor-based file writer!
PART 2
Objective:
To implement file writing and reading using a single constructor in one class to perform both tasks
sequentially.
Key Points:
- Only one class is used: FileHandler.
- The constructor performs both file writing and reading.
- Shows how multiple responsibilities can be combined for simplicity.
- Utilizes C++ <fstream> for I/O.
Main Idea:
The constructor of a single class handles both writing to and reading from a file.
Conclusion:
This method is ideal for quick file operations where separation of logic is not necessary.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class FileHandler
{ public:
FileHandler(const string& filename, const string& content) {
ofstream outfile(filename); if (outfile.is_open())
{ outfile << content; cout << "Writing
completed.\n"; outfile.close(); } else
{ cout << "Failed to open file for writing.\n";
return;
}
ifstream infile(filename);
string line; if (infile.is_open()) {
cout << "Reading from file:\n";
while (getline(infile, line))
{ cout << line << endl;
} infile.close(); } else
{ cout << "Failed to open file for reading.\
n";
};
int main() {
FileHandler handler("sample2.txt", "This is a combined file read/write using constructor.");
return 0;
Outcome:
Writing completed.
Reading from file:
This is a combined file read/write using constructor.