C++ Files

C++ Files (File Handling)

To write to or read from files in C++, you need to use the <fstream> library.

This library provides three main classes for file handling:


1. Writing to a File

To create a file and write to it, use the ofstream class.

Write File Example

#include <iostream>
#include <fstream> // Include fstream library
using namespace std;

int main() { // Create and open a text file ofstream MyWriteFile("filename.txt");

// Write text to the file using the insertion operator (<<) MyWriteFile << "Files can be tricky, but it is fun enough!";

// Close the file when done MyWriteFile.close();

cout << "File written successfully.\n"; return 0; }

Why close the file? Always use .close() when you are done. It frees up memory and system resources, and ensures that the data is physically saved to the hard drive.


2. Reading from a File

To read from an existing file, use the ifstream class and a while loop together with the getline() function to read the file line by line.

Read File Example

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() { // Create a text string variable to hold each line from the file string myText;

// Read from the text file ifstream MyReadFile("filename.txt");

// Use a while loop together with getline() to read file line by line while (getline(MyReadFile, myText)) { // Output the text from the file cout << myText << "\n"; }

// Close the file MyReadFile.close(); return 0; }

If you try to read a file that doesn't exist, C++ will not crash, but the while loop will never execute. It is good practice to check if the file opened successfully using if (MyReadFile.is_open()).


Exercise

?

Which class is used specifically to write data to a file?