Mark As Completed Discussion

File Handling

File handling in C++ involves reading from and writing to files. This is useful for tasks such as storing data, reading configuration files, or processing large datasets.

To perform file handling operations in C++, include the <fstream> library. Here's an example program that demonstrates how to write to and read from a file:

TEXT/X-C++SRC
1{{code}}

In this example:

  • We use the ofstream class to write data to a file. First, we create an ofstream object and open the file using the open() function. Then, we use the << operator to write the string "Hello, World!" to the file. Finally, we close the file using the close() function.

  • We use the ifstream class to read data from a file. First, we create an ifstream object and open the file using the open() function. Then, we use the getline() function in a loop to read each line of the file and print it to the console. Finally, we close the file using the close() function.

You can run the above program and observe the output to see the results of the file handling operations. Feel free to experiment and modify the code to further explore file handling in C++.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment