File Handling: Learn how to perform file operations in C++, including reading and writing to files, opening and closing files, and file input/output using fstream library.

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.

Related posts:

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading