Tutorial: Reading and Writing Files in C++

File handling is an essential skill in C++ for tasks like saving data, configuration management, or processing input and output. C++ provides the <fstream> library for file operations, including reading from and writing to files.


1. Required Header: <fstream>

Include the <fstream> header to work with files in C++.

#include <fstream>
#include <iostream>
#include <string>

using namespace std::

2. Opening Files

Files can be opened in different modes using the ifstream (input), ofstream (output), or fstream (both input and output).

  • File Modes:
    • ios::in – Open for reading.
    • ios::out – Open for writing.
    • ios::app – Append to the end of the file.
    • ios::trunc – Truncate the file (delete contents if it exists).

3. Writing to a File

Use ofstream to write data to a file.

Example: Writing to a File

#include <fstream>
#include <iostream>


int main() {
ofstream outFile("example.txt"); // Create and open the file

if (!outFile) {
cerr << "Error: Could not open the file for writing." << endl;
return 1;
}

outFile << "Hello, World!" << endl; // Write to the file
outFile << "This is a file write example in C++." << endl;

outFile.close(); // Close the file
cout << "Data written to file successfully." << endl;

return 0;
}
  • Output: A file example.txt will contain:
    Hello, World! This is a file write example in C++.

4. Reading from a File

Use ifstream to read data from a file.

Example: Reading from a File

#include <fstream>
#include <iostream>


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

if (!inFile) {
cerr << "Error: Could not open the file for reading." << endl;
return 1;
}

string line;
while (getline(inFile, line)) { // Read line by line
cout << line << endl; // Print the line to console
}

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

5. Reading and Writing Together

Use fstream to perform both input and output.

Example: Reading and Appending to a File

#include <fstream>
#include <iostream>


int main() {
fstream file("example.txt", ios::in | ios::out | ios::app);

if (!file) {
cerr << "Error: Could not open the file." << endl;
return 1;
}

// Write to the file
file << "Appending a new line!" << endl;

// Move the cursor back to the beginning to read the file
file.seekg(0);

// Read the file
string line;
cout << "File contents:" << endl;
while (getline(file, line)) {
cout << line << endl;
}

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

6. Binary File Operations

For reading and writing raw binary data, use ios::binary mode.

Example: Writing and Reading Binary Data

#include <fstream>
#include <iostream>


int main() {
const char data[] = "Binary Data";

// Write binary data
ofstream outFile("binaryfile.bin", ios::binary);
outFile.write(data, sizeof(data));
outFile.close();

// Read binary data
char buffer[50];
ifstream inFile("binaryfile.bin", ios::binary);
inFile.read(buffer, sizeof(data));
inFile.close();

cout << "Read from binary file: " << buffer << endl;

return 0;
}

7. Checking File Existence

Before reading or writing, it’s often useful to check if the file exists.

Example: File Existence Check

#include <fstream>
#include <iostream>


int main() {
ifstream file("example.txt");

if (file) {
cout << "File exists." << endl;
} else {
cout << "File does not exist." << endl;
}

return 0;
}

8. Common Errors and Debugging Tips

  1. File Not Opening: Ensure the file path is correct and you have proper permissions.
  2. Incorrect File Mode: Use the appropriate mode (ios::in, ios::out, etc.).
  3. File Already Open: Always close files after use to avoid conflicts.

Practice Problems

  1. Write a program that reads integers from a file, calculates their sum, and writes the result to a new file.
  2. Write a program that copies the content of one file to another.
  3. Write a program that reads a file, counts the number of lines, and prints it.

Summary

  • Use <fstream> for file operations.
  • ofstream for writing, ifstream for reading, and fstream for both.
  • Always check if a file was successfully opened before performing operations.
  • Remember to close the file after you’re done!

Mastering file I/O in C++ is critical for working with data in real-world applications. Happy coding!

Scroll to Top