Skip to content

File streams

File streams

C++ provides file streams to perform output and input of characters to/from files. These classes are derived directly or indirectly from the classes std::istream and std::ostream.

We have already used objects whose types were these classes: std::cin is an object of class std::istream and std::cout is an object of class ostream.

We can use our file streams the same way we are already used to use std::cin and std::cout, with the only difference that we have to associate these streams with physical files.:

1
2
3
4
5
6
std::vector<int> numbers;
constexpr size_t n = 15;
numbers.resize(n);
for (size_t i = 0; i < n; ++i) {
    numbers[i] = i * 1000 + 1;
}

1
2
3
4
5
std::ofstream fout("numbers.txt");
for (int number : numbers) {
    fout << number << " ";
}
fout.close();

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
std::vector<int> m_numbers;
std::ifstream fin("numbers.txt");
do {
    int x;
    fin >> x;
    if (fin) {
        m_numbers.emplace_back(x);
    }
} while (fin);
fin.close();

1
2
3
4
5
6
7
8
for (const auto &number : numbers) {
    std::cout << number << " ";
}
std::cout << '\n';
for (const auto &number : m_numbers) {
    std::cout << number << " ";
}
std::cout << '\n';

1
2
3
4
5
6
7
fout.open("numbers.bin", std::ios::binary);
for (int &number : numbers) {
    char *pointer_to_number = (char *)&number;
    size_t bytes_per_number = sizeof(number);
    fout.write(pointer_to_number, bytes_per_number);
}
fout.close();

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
m_numbers.clear();
fin.open("numbers.bin", std::ios::binary);
for (size_t i = 0; i < numbers.size(); ++i) {
    int x;
    char *pointer_to_number = (char *)&x;
    size_t bytes_per_number = sizeof(x);
    fin.read(pointer_to_number, bytes_per_number);
    m_numbers.emplace_back(x);
}
fin.close();

1
2
3
4
5
6
7
8
for (const auto &number : numbers) {
    std::cout << number << " ";
}
std::cout << '\n';
for (const auto &number : m_numbers) {
    std::cout << number << " ";
}
std::cout << '\n';

1
2
3
4
std::cout << "File size (text): "
          << std::filesystem::file_size("numbers.txt") << " bytes\n";
std::cout << "File size (binary): "
          << std::filesystem::file_size("numbers.bin") << " bytes\n";

Share Snippets