WikiGalaxy

Personalize

Introduction to C++

What is ?

The library in C++ is a part of the standard input/output library that provides facilities for file handling. It includes classes for reading from and writing to files, enabling persistent data storage and retrieval.

Basic File Operations

Opening and Closing Files

In C++, files are opened using the open() function and closed using the close() function. The fstream class provides these functionalities.


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

int main() {
    fstream file;
    file.open("example.txt", ios::out);
    if (file.is_open()) {
        cout << "File opened successfully." << endl;
        file.close();
    } else {
        cout << "Failed to open file." << endl;
    }
    return 0;
}
    

Writing to a File

Using ofstream

The ofstream class is used for writing to files. It provides an easy interface to output data to a file.


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

int main() {
    ofstream file("output.txt");
    if (file.is_open()) {
        file << "Hello, World!" << endl;
        file.close();
        cout << "Data written to file." << endl;
    } else {
        cout << "Failed to open file for writing." << endl;
    }
    return 0;
}
    

Reading from a File

Using ifstream

The ifstream class is used for reading from files. It allows you to input data from a file into your program.


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

int main() {
    ifstream file("input.txt");
    string line;
    if (file.is_open()) {
        while (getline(file, line)) {
            cout << line << endl;
        }
        file.close();
    } else {
        cout << "Unable to open file for reading." << endl;
    }
    return 0;
}
    

Appending to a File

Using ios::app

To append data to an existing file, open the file in append mode using ios::app. This mode ensures that new data is added to the end of the file without overwriting existing content.


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

int main() {
    ofstream file("output.txt", ios::app);
    if (file.is_open()) {
        file << "Appending this line." << endl;
        file.close();
        cout << "Data appended to file." << endl;
    } else {
        cout << "Failed to open file for appending." << endl;
    }
    return 0;
}
    

Binary File Operations

Reading and Writing Binary Files

Binary files store data in a format that is not human-readable but is efficient for computer processing. Use ios::binary mode for binary file operations.


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

int main() {
    // Writing binary data
    ofstream outFile("data.bin", ios::binary);
    int num = 12345;
    outFile.write(reinterpret_cast<char*>(&num), sizeof(num));
    outFile.close();

    // Reading binary data
    ifstream inFile("data.bin", ios::binary);
    int readNum;
    inFile.read(reinterpret_cast<char*>(&readNum), sizeof(readNum));
    inFile.close();

    cout << "Read number: " << readNum << endl;
    return 0;
}
    

Checking File Status

Using is_open()

The is_open() function checks whether a file is successfully opened. It returns true if the file is open, otherwise false.


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

int main() {
    ifstream file("test.txt");
    if (file.is_open()) {
        cout << "File is open." << endl;
    } else {
        cout << "File is not open." << endl;
    }
    file.close();
    return 0;
}
    

Error Handling in File Operations

Using fail() and bad()

The fail() function checks if a file operation failed, while bad() checks for serious errors. These functions help in robust error handling.


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

int main() {
    ifstream file("nonexistent.txt");
    if (file.fail()) {
        cout << "File operation failed." << endl;
    } else {
        cout << "File operation succeeded." << endl;
    }
    file.close();
    return 0;
}
    

File Positioning

Using seekg() and seekp()

The seekg() and seekp() functions are used to set the position of the next character to be read or written in a file. These functions are essential for random file access.


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

int main() {
    fstream file("example.txt", ios::in | ios::out | ios::binary);
    file.seekp(5); // Move write pointer to the 5th position
    file << "X";
    file.seekg(0); // Move read pointer to the start
    char ch;
    file.get(ch);
    cout << "First character: " << ch << endl;
    file.close();
    return 0;
}
    

File Buffers and Synchronization

Using sync()

The sync() function is used to synchronize the associated buffer with the file. This ensures that all pending output operations are completed before the program proceeds.


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

int main() {
    fstream file("sync_example.txt", ios::out);
    file << "Data before sync.";
    file.flush(); // Alternatively, you can use file.sync();
    cout << "Data synchronized to file." << endl;
    file.close();
    return 0;
}
    
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025