File Input and Output in C++

In C++, File Input and Output refers to the program’s operations for reading (input) and writing (output) data to and from files on disk. This is a crucial feature in many practical applications, such as:

  • Reading configuration files

  • Saving user data (e.g., game saves, score records)

  • Importing/exporting text or data files

  • Logging, etc.

🎯 1. What Library is Used for File Operations in C++?

The C++ Standard Library provides the <span><fstream></span> header file, which includes classes for file input and output. It is a tool specifically designed for file operations in the C++ Standard Library, based on the concept of streams, similar to <span>cin/cout</span>.

✅ 2. Three Core Classes in <span><fstream></span>

Class Name

Function

Description

<span>std::ifstream</span>

Input File Stream

Used to read data from a file (input), equivalent to <span>cin</span> but reading from a file

<span>std::ofstream</span>

Output File Stream

Used to write data to a file (output), equivalent to <span>cout</span> but writing to a file

<span>std::fstream</span>

Input & Output File Stream

Can read from and write to a file, used flexibly

🧠 All of them inherit from the stream classes in <span>iostream</span>, so their usage is similar to <span>cin/cout</span>, but the operation target is files instead of the console.

📂 3. Basic Steps for File Operations (Using <span>ofstream</span> and <span>ifstream</span> as Examples)

1. Include Header Files

#include <fstream> // File stream operations
#include <iostream> // Optional, for console output prompts
using namespace std;




2. Create File Stream Objects

  • Write to file → <span>ofstream outFile("filename.txt");</span>

  • Read from file → <span>ifstream inFile("filename.txt");</span>

  • Read and write to file → <span>fstream file("filename.txt", mode);</span>

3. Open the File (Usually Automatically Done in the Constructor)

You can also manually call the <span>.open("filename")</span> method.

4. Operate on the File: Write or Read Data

  • Writing: Use the <span><<</span> operator, just like <span>cout</span>

  • Reading: Use the <span>>></span> operator, just like <span>cin</span>

5. Close the File (Usually Automatically Done in the Destructor, but Can Also Be Manually Called with <span>.close()</span>)

✅ 4. 🔧 Example 1: Using <span>ofstream</span> to Write to a File (Output to File)

📝 Function: Write Some Text to the File <span>example.txt</span>

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

int main() {
// Create an ofstream object, open the file "example.txt" (create if it does not exist)
ofstream outFile("example.txt");  // Default mode is ios::out (write)

if (!outFile) {
        cerr << "Unable to open file for writing!" << endl;
return 1;
    }

// Write data to the file (using <<, similar to cout)
    outFile << "Hello, file writing!" << endl;
    outFile << "This is the second line." << endl;
    outFile << "C++ file operations are powerful!" << endl;

// Close the file (optional, automatically closed on destruction)
    outFile.close();

    cout << "Data has been successfully written to file example.txt" << endl;

return 0;
}



🔍 After Running:

  • The program will generate a <span>example.txt</span> file in your project directory (or the directory where the executable is located)

  • The file will contain three lines of text

✅ 5. 🔧 Example 2: Using <span>ifstream</span> to Read from a File (Input from File)

📝 Function: Read Content from the <span>example.txt</span> File and Display on Screen

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

int main() {
ifstream inFile("example.txt");  // Open the file for reading

if (!inFile) {
        cerr << "Unable to open file for reading! Please confirm if the file exists." << endl;
return 1;
    }

    string line;
    cout << "File content is as follows:" << endl;

// Read file content line by line
while (getline(inFile, line)) {  // getline is used to read a line (including spaces)
        cout << line << endl;
    }

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



🔍 Running Effect:

  • The program will read each line of content from <span>example.txt</span> and print it to the console

  • Used <span>getline(inFile, line)</span> to read a line of text (can include spaces)

✅ 6. 🔧 Example 3: Using <span>fstream</span> to Read and Write to a File

If you want to open a file and both read and write, you can use <span>fstream</span> and specify the open mode.

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

int main() {
// Open the file (create if it does not exist), mode for read and write (in | out)
fstream file("data.txt", ios::in | ios::out | ios::trunc);

if (!file) {
        cerr << "Unable to open file!" << endl;
return 1;
    }

// Write data
    file << "This is the first line of written content." << endl;
    file << "This is the second line." << endl;

// Move the file pointer to the beginning of the file, ready to read
    file.seekg(0, ios::beg);

// Read the content just written
    string line;
    cout << "Reading file content:" << endl;
while (getline(file, line)) {
        cout << line << endl;
    }

    file.close();
return 0;
}



🧠 <span>seekg(0, ios::beg)</span><span> moves the </span><strong><span>read pointer to the beginning of the file</span></strong><span>, allowing you to read the content just written again.</span>

🧠 7. File Open Modes

When opening a file, you can specify different modes. Common modes are as follows (can be combined, such as <span>ios::in | ios::out</span>):

Mode

Description

<span>ios::in</span>

Open the file for reading (input)

<span>ios::out</span>

Open the file for writing (output), overwrites the original file

<span>ios::app</span>

Append mode, content written will be added to the end of the file (not overwrite)

<span>ios::ate</span>

Open the file and position to the end of the file (usually combined with other modes)

<span>ios::trunc</span>

If the file already exists, clears the file content (default used with <span>out</span>)

<span>ios::binary</span>

Open the file in binary mode (non-text mode)

For example:

  • <span>ofstream file("data.txt", ios::out | ios::app);</span> → Write, but append to the end of the file

  • <span>ifstream file("data.txt", ios::in);</span> → Open in read-only mode

✅ 8. Summary: Key Points of C++ File Input and Output (fstream)

Function

Class

Description

Common Operations

Write to File

<span>ofstream</span>

Output to file (write)

<span>outFile << "content";</span>

Read from File

<span>ifstream</span>

Read from file

<span>inFile >> variable;</span> or <span>getline(inFile, str);</span>

Read and Write to File

<span>fstream</span>

Can read and write

Combine as needed <span>ios::in | ios::out</span>

Open File

Constructor or <span>.open()</span>

Specify file name and mode

<span>ifstream file("a.txt");</span>

Close File

<span>.close()</span>

Generally can be omitted (automatically closed on destruction)

<span>file.close();</span>

Read a Line (Including Spaces)

<span>getline(stream, string)</span>

Recommended for text reading

<span>getline(inFile, line);</span>

File Open Modes

<span>ios::in</span>, <span>ios::out</span>, <span>ios::app</span>, <span>ios::trunc</span>, etc.

Control the file opening method

Used in combination, such as <span>ios::in | ios::out</span>

Leave a Comment