C++ ostream sometimes fails to open file in a for loop

  c++, ostream

Here is the minimal reproducible code:

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

using namespace std;


const string TEST_FILE_PATH = "output.txt";

void write_to_file(string path, string line);
void generate_passwords(string file);

int main()
{
    generate_passwords(TEST_FILE_PATH);
    return 0;
}

void generate_passwords(string file)
{
    int count = 1;
    for (int len = 1; len <= 100; len++)
    {
        for (int i = 0; i < 100; i++)
        {
            write_to_file(file, to_string(count) + " : ");
            count++;
        }
    }
}

void write_to_file(string path, string line)
{
    ofstream file;
    file.open(path, ios::out | ios::app);

    cout << "writing line : " << line << endl;

    if (file.is_open())
    {
        cout << "file is open " << endl;
        file << line << 'n';
        cout << "written..." << endl;
    }
    else {

        cout << "FILE NOT OPEN" << endl;
    }

    file.close();
}

This is a stripped-down version of my full code and it reproduces the same error.
With this code, I expect exactly 10,000 lines to be written to output.txt. However, it sometimes skips a random number of lines :

enter image description here (See how it skips numbers 6466 to 6509)

The console prints for these numbers "FILE NOT OPEN".

This rarely happens with fewer iterations, but occurs very often with large numbers of iterations.

What could be the issue?

Source: Windows Questions C++

LEAVE A COMMENT