1

When I make array of 550 (or more) objects (which contain ofstreams), first 509 objects are 'good' ones (with files etc.), but further objects are 'wrong'.
Have no clue what I made wrong.
Maybe special initialization of ofstream is needed?

This issue is for both 'Debug' and 'Release' versions.
Code (C++) (compiled under Microsoft Visual C++ 2012):

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

class C {
    int n;
    ofstream f;
public:
    C() {n=1;}
    void Bind(char* filename);
};

void C::Bind(char* filename) {
    f.open(filename,ios::binary);
    if (!f)  cout << "file " << filename << " Error..." << endl;
}

int main() {
    C *c = new C[550];
    for (int i=0;i<550;i++) {
        char filename[256];
        sprintf_s(filename, "file-%03d.bin", i);
        c[i].Bind(filename);
    }
    return 0;
}

Output is:

file file-509.bin Error...
file file-510.bin Error...
file file-511.bin Error...
file file-512.bin Error...
file file-513.bin Error...
... ... ...


What's the magic of these 509 files?
How should I correct this code for array with 550 (or more) objects?

Thank you!

Oleg567
  • 239
  • 2
  • 11
  • 1
    A well placed `perror` may help you here. Probably ran out of file handles. Windows should allow millions of handles, but the C runtime may be capped at 512 or similar number. – user4581301 Oct 02 '17 at 23:21
  • Note that the best solution is probably to change your design so that you don't open so many files at once. – interjay Oct 02 '17 at 23:22
  • @user4581301, thank you, so I can freely change conception from ofstream to HANDLE (with CreateFile(...), WriteFile(...) etc.)? – Oleg567 Oct 02 '17 at 23:25
  • 1
    Give the suggestions in the linked duplicate a try before using `CreateFile` you may find yourself opening yourself up to a whole new set of problems. – user4581301 Oct 02 '17 at 23:27
  • @interjay, thank you for helpful link; the _setmaxstdio(1000) can help for quick fix; and I'll think about redesign for future. – Oleg567 Oct 02 '17 at 23:40

0 Answers0