Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

File Streams in C++

Introduction

File handling in C++ is essential for many applications. File streams allow you to read from and write to files easily. In C++, the fstream library provides the necessary tools for file handling. This tutorial will guide you through the basics of file streams, along with detailed examples.

Including the fstream Library

To work with file streams in C++, you need to include the fstream library. The fstream library provides three classes:

  • ifstream - for reading from files
  • ofstream - for writing to files
  • fstream - for both reading and writing to files

Here is how you include the fstream library:

#include <fstream>

Reading from a File

To read from a file, you use the ifstream class. Below is an example that demonstrates how to read the contents of a file and print them to the console:

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

int main() {
    ifstream inputFile("example.txt");
    string line;

    if (inputFile.is_open()) {
        while (getline(inputFile, line)) {
            cout << line << endl;
        }
        inputFile.close();
    } else {
        cout << "Unable to open file" << endl;
    }
    return 0;
}

In this code:

  • We include the fstream and iostream libraries.
  • We create an ifstream object named inputFile and open example.txt.
  • We use a while loop with getline to read each line from the file and print it.
  • Finally, we close the file using inputFile.close().

Writing to a File

To write to a file, you use the ofstream class. Below is an example that demonstrates how to write some text to a file:

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

int main() {
    ofstream outputFile("example.txt");

    if (outputFile.is_open()) {
        outputFile << "This is a line." << endl;
        outputFile << "This is another line." << endl;
        outputFile.close();
    } else {
        cout << "Unable to open file" << endl;
    }
    return 0;
}

In this code:

  • We include the fstream and iostream libraries.
  • We create an ofstream object named outputFile and open example.txt.
  • We write two lines to the file using the insertion operator <<.
  • Finally, we close the file using outputFile.close().

Reading and Writing to a File

To read from and write to a file simultaneously, you use the fstream class. Below is an example that demonstrates how to open a file for both reading and writing:

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

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

    if (file.is_open()) {
        file << "Appending a new line." << endl;
        string line;
        file.seekg(0); // Go to the beginning of the file
        while (getline(file, line)) {
            cout << line << endl;
        }
        file.close();
    } else {
        cout << "Unable to open file" << endl;
    }
    return 0;
}

In this code:

  • We include the fstream and iostream libraries.
  • We create an fstream object named file and open example.txt with ios::in (read), ios::out (write), and ios::app (append) modes.
  • We append a new line to the file using the insertion operator <<.
  • We use seekg(0) to move the file pointer to the beginning of the file.
  • We read and print each line from the file using a while loop and getline.
  • Finally, we close the file using file.close().

Binary File I/O

In addition to text files, C++ also supports binary file I/O. To read from and write to binary files, you need to use the ios::binary flag. Below is an example that demonstrates how to write and read binary data:

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

struct Data {
    int id;
    char name[20];
};

int main() {
    Data data = {1, "Example"};

    ofstream outputFile("binary.dat", ios::binary);
    if (outputFile.is_open()) {
        outputFile.write(reinterpret_cast<char*>(&data), sizeof(Data));
        outputFile.close();
    }

    Data readData;
    ifstream inputFile("binary.dat", ios::binary);
    if (inputFile.is_open()) {
        inputFile.read(reinterpret_cast<char*>(&readData), sizeof(Data));
        inputFile.close();
    }

    cout << "ID: " << readData.id << ", Name: " << readData.name << endl;
    return 0;
}

In this code:

  • We include the fstream and iostream libraries.
  • We define a Data structure with an int and a char array.
  • We create a Data object named data and initialize it.
  • We open a binary file named binary.dat for writing using ofstream with the ios::binary flag.
  • We write the data object to the file using write.
  • We read the data back from the file into a Data object named readData using ifstream with the ios::binary flag and read.
  • Finally, we print the contents of readData.

Conclusion

File streams in C++ provide powerful and flexible ways to handle file I/O operations. Whether dealing with text or binary files, the fstream library covers a wide range of functionalities to meet various needs. By mastering file streams, you can significantly enhance the capabilities of your C++ programs.