how does this work?

double E=5.;
double F=5.;
char filename[]="";
stringstream stream;
stream <<"E="<< E <<"_F="<<F<<".txt";
stream >> filename;
FILE*pFile;
pFile=fopen(filename, "w");

filename is an empty char and i overwrite it with a string?
fopen() accepts filename as argument.
it works, i dont know why, but it definitely works.
No, it does not work. It merely appears to work. That is most unfortunate.

In reality the input operation writes not only the single element of the array "filename" (which contains 0), but also overwrites several bytes that happen to be after the array in memory. We have no idea what is overwritten, so we don't know how serious memory corruption it creates.


Why do you use fopen? You seem to be able to use streams. Why do you use stringstream instead of ostringstream? The ostringstream can hand out the (std::)string directly.
i need a file with that specific name
but i dont know how to include the variables E and F in the filename other than using this.
fopen needs a const char, but the length of my file name isnt always the same size, so i
somehow need to use strings.
ok i found something

string name;
stringstream stream;
stream <<"E="<< E <<"_F="<<F<<".txt";
stream >> name;
const char * filename = name.c_str();
FILE*pFile;
pFile=fopen(filename, "w");

c_str() does the trick
Good.
1
2
3
4
std::ostringstream filename;
filename << "E=" << E << "_F=" << F << ".txt";
FILE* pFile;
pFile = fopen( filename.str().c_str(), "w");

But why fopen? Why not ofstream?
1
2
3
std::ostringstream filename;
filename << "E=" << E << "_F=" << F << ".txt";
std::ofstream oFile( filename.str() );

dunno
i always used fopen
is ofstream any better?
ofstream is a stream
stringstream is a stream
cout is a stream

All streams can be used almost the same way. You can even pass a stream reference into a function and the function doesn't know whether you call it with a file or cout.
Topic archived. No new replies allowed.