Lesson 15-C++ File Operations

File Stream Classes

The fstream class is part of the iostream library and inherits from the iostream class, so it can be used both as an input stream and an output stream. The fstream class has two derived classes:

  • ifstream: Used to read data from a file.
  • ofstream: Used to write data to a file.

Opening a File

Before performing file operations, you need to open a file first. You can open a file in the following ways:

Constructor:

  • std::ifstream file("filename");
  • std::ofstream file("filename");

Member function open:

  • file.open("filename", std::ios_base::mode);

File Modes

The open function takes two parameters: the filename and the file mode. The file mode is an enumeration value from std::ios_base and can be one or a combination of the following:

  • in: Open the file in input mode.
  • out: Open the file in output mode.
  • app: Append mode, adds data to the end of the file.
  • ate: Seek to the end of the file.
  • binary: Open the file in binary mode.
  • trunc: If the file exists, truncate it; if it does not exist, create a new file.

File Operation Examples

Opening a File

#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("example.txt", std::ios::out | std::ios::trunc);
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    file << "Hello, World!";
    file.close();

    return 0;
}

Writing to a File

You can use the << operator to write data to a file. The fstream class supports writing various data types, including strings, integers, floating-point numbers, etc.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("example.txt");
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    file << "Hello, World!" << std::endl;
    file << "This is a test." << std::endl;
    file.close();

    return 0;
}

Reading from a File

You can use the >> operator to read data from a file. Similarly, the fstream class supports reading various data types.

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("example.txt");
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }

    file.close();

    return 0;
}

Binary File Operations

For binary files, you can use the read and write member functions to read and write data.

#include <iostream>
#include <fstream>

struct Data {
    int id;
    float value;
};

int main() {
    std::ofstream file("data.bin", std::ios::out | std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    Data data = {1, 3.14};
    file.write(reinterpret_cast<const char*>(&data), sizeof(Data));
    file.close();

    std::ifstream readFile("data.bin", std::ios::in | std::ios::binary);
    if (!readFile.is_open()) {
        std::cerr << "Failed to open the file for reading." << std::endl;
        return 1;
    }

    Data readData;
    readFile.read(reinterpret_cast<char*>(&readData), sizeof(Data));

    std::cout << "ID: " << readData.id << ", Value: " << readData.value << std::endl;

    readFile.close();

    return 0;
}

File Position Pointer

The file position pointer indicates the current read/write position. You can use the following member functions to control the file position pointer:

  • seekg: Sets the position of the input file pointer.
  • seekp: Sets the position of the output file pointer.
  • tellg: Gets the position of the input file pointer.
  • tellp: Gets the position of the output file pointer.
#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("example.txt", std::ios::out | std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    file << "Hello, World!" << std::endl;
    file << "This is a test." << std::endl;

    // Move the file pointer to the beginning
    file.seekp(0, std::ios::beg);

    // Append data at the beginning
    file << "Additional text: ";

    file.close();

    return 0;
}

File Error Detection

During file operations, various errors may occur, such as file not found, disk full, etc. The fstream class provides several member functions to detect the state of the file stream:

  • good: Returns true if the stream has no errors.
  • fail: Returns true if the stream is in a failed state.
  • eof: Returns true if the stream has reached the end of the file.
  • bad: Returns true if the stream is in a severe error state.
#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("example.txt");
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }

    if (file.fail()) {
        std::cerr << "An error occurred while reading the file." << std::endl;
    } else if (file.eof()) {
        std::cout << "End of file reached." << std::endl;
    }

    file.close();

    return 0;
}

File Buffering

File buffering is a mechanism where the operating system temporarily stores file data to improve performance. The C++ standard library allows you to control the buffering behavior of file streams.

You can use std::ios_base::sync_with_stdio(false) to disable synchronization with standard I/O, thereby improving performance. Additionally, you can use the std::ios_base::rdbuf() method to get or set the buffer.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("example.txt");
    file.rdbuf()->pubsetbuf(nullptr, 0);  // Disable buffering
    file << "Hello, World!";

    file.close();

    return 0;
}

File Locking

In multi-threaded or multi-process environments, file locking can prevent multiple processes from modifying the same file simultaneously. The C++ standard library itself does not support file locking, but you can use platform-specific methods to achieve it.

Using Windows API for File Locking

#include <windows.h>
#include <iostream>
#include <fstream>

int main() {
    HANDLE hFile = CreateFileA("example.txt",
                               GENERIC_READ | GENERIC_WRITE,
                               0,  // No sharing
                               NULL,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL,
                               NULL);

    if (hFile == INVALID_HANDLE_VALUE) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    OVERLAPPED overlapped = {0};
    if (!LockFile(hFile, 0, 0, 1024, 0)) {
        std::cerr << "Failed to lock the file." << std::endl;
        CloseHandle(hFile);
        return 1;
    }

    std::ofstream file("example.txt", std::ios::out | std::ios::binary);
    file << "Hello, World!";

    if (!UnlockFile(hFile, 0, 0, 1024, 0)) {
        std::cerr << "Failed to unlock the file." << std::endl;
    }

    CloseHandle(hFile);
    file.close();

    return 0;
}

Complex File Operations

Sometimes, you may need to perform more complex file operations, such as reading large files, handling file metadata, etc.

Reading Large Files For large files, reading all data at once may consume a lot of memory. You can read the file in chunks.

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("largefile.txt", std::ios::in | std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    const size_t bufferSize = 4096;
    char buffer[bufferSize];

    while (file.read(buffer, bufferSize)) {
        std::cout.write(buffer, file.gcount());
    }

    file.close();

    return 0;
}

Handling File Metadata You can use the std::filesystem library to get file metadata, such as file size, last modification time, etc.

#include <iostream>
#include <filesystem>

int main() {
    std::filesystem::path path("example.txt");

    if (!std::filesystem::exists(path)) {
        std::cerr << "File does not exist." << std::endl;
        return 1;
    }

    std::cout << "File size: " << std::filesystem::file_size(path) << " bytes" << std::endl;
    std::cout << "Last modified: " << std::filesystem::last_write_time(path) << std::endl;

    return 0;
}
Share your love