Reputation: 183
Clarification: This is not a duplicate because
- I am also closing the files after opening them.
- The program hangs after 20-40 iterations, not a few hundred as said in the other question
I was trying to create a simple puzzle in the form of 2000 files that will have numbers stored inside them. I needn't get into the details but basically it required a loop that would open and close 2000 files. However, after 20-40 iterations, the program would unexpectedly start hanging and not resume, neither give any error, etc. I went through the syntax of the program and everything else looks fine, so is the problem simply that C++ does not support such a large number of files?
Code:
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
ofstream out;
char a[4];
int i,j,k,n,no[5],queue[2000],q=1; //n = no of nos, q=first free index in queue
queue[0]=1;
bool successful;
srand(time(NULL));
for(i=0;i<2000;++i)
{
cout<<"\n\nIteration "<<i;
snprintf(a,sizeof(a),"%d",queue[i]);
out.open(a);
cout<<"\nFile "<<a<<" opened\n";
n=rand()%4+2;
cout<<n<<" random nos to be generated";
for(j=0;j<n;++j)
{
no[j]=rand()%2000+1;
do
{
successful=true;
for(k=0;k<i;++k)
if(queue[k]==no[j])
successful=false;
} while (!successful);
}
cout<<"\nNos selected ";
for(j=0;j<n;++j)
cout<<no[j]<<" ";
for(j=0;j<n;++j)
out<<no[j]<<"\n";
cout<<"\nWritten to file";
out.close();
out.open("logs", ios::app);
cout<<"\nLogs opened";
out<<"\n\n"<<i<<"\n ";
for(j=0;j<n;++j)
out<<no[j]<<"\n ";
out.close();
cout<<"\nLog entry made";
for(j=0;j<n;++j)
queue[q+j]=no[j];
q+=n;
cout<<"\nAppended to queue, new queue length: "<<q<<"\n\n";
}
}
Upvotes: 1
Views: 157
Reputation: 1481
The problem has nothing to do with opening files. The program hangs in an infinite loop at lines 28-34 while(!successful).
Upvotes: 1