I have a code for outputting to a file from a 2D vector Kvec. The name of the file is inputted in the string s, and I'm using sprintf to convert the int into the char to be inputted into the string. Then I used s.c_str() to input it as the name of the file I want to open. So when I try running the code I get a segfault when I try to open the file using foo.open(). It's got such little scope for error that I'm baffled where could the mistake be.
I've already used this technique for working on the strings to open files so I know sprintf and s.push_back() work. Where am I going wrong?
fstream foo;
string s;
char g[10],j[10];
int b=0;
sprintf(j,"L_%dLprime_%dM_%dMprime_%d",L,Lprime,M,Mprime);
for(int i=0;i<(int)strlen(j);i++)
s.push_back(j[i]);
for( int D = 0; D < 1000; D++ )
{
s+="MSF-Dval";
sprintf(g,"%d",D);
for(int i=0; i<(int)strlen(g); i++)
s.push_back(g[i]);
s+=".dat";
foo.open(s.c_str(), ios::in | ios::out | ios::binary );
cout<<"Is this working?"<<endl;
b = 0;
for(L1=abs(L-D);L1<L1max;L1++)
{
if( (D>abs(L+L1) || D<abs(L-L1)) && b == 0)
{
if(remove(s.c_str())!=0)
cout<<"error deleting file";
break;
}
b = 1;
if(foo.is_open())
{
foo << L1 << " "<<Kvec.at(L1).at(L1+D-abs(L-L1)).re<<" "<<Kvec.at(L1).at(L1+D-abs(L-L1)).im<<endl;
}
else
cout<<"not open";
}
foo.close();
s.erase(8,4 + (int)strlen(g));
}