Certainly! Here’s an alternative approach to accomplish the same task.
In this solution, we will use the fstream
library to handle file operations.
Here’s a sample code to perform the task:
1 #include <iostream>
2 #include <fstream>
3 #include <string>
4
5void writeToFile(std::string data) {
6 std::ofstream outfile;
7 outfile.open("sample.txt", std::ios_base::app);
8 if (outfile.is_open()) {
9 outfile << data << std::endl;
10 outfile.close();
11 } else {
12 std::cout << "Unable to open file." << std::endl;
13 }
14}
15
16void readFromFile() {
17 std::ifstream infile;
18 infile.open("sample.txt");
19 if (infile.is_open()) {
20 std::string line;
21 while (getline(infile, line)) {
22 std::cout << line << std::endl;
23 }
24 infile.close();
25 } else {
26 std::cout << "Unable to open file." << std::endl;
27 }
28}
29
30int main() {
31 writeToFile("Hello, World!");
32 writeToFile("Welcome to File Handling.");
33 readFromFile();
34 return 0;
35}
In this code, the writeToFile
function appends the provided data to the “sample.txt” file. The readFromFile
function reads the data from the “sample.txt” file and prints it line by line.
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.