two similar bits of code using stringstream; only one works

I'm trying to write a program which opens a text file with a name of the form "file0.txt" or "file20.txt" or anything like that. I mucked about with a few methods before finding one that worked, which involved stringstreams:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void open_file(int id) {
   std::stringstream stream;
   stream << "file" << id << ".txt";
   char *filename, *temp;
   stream >> temp;
   filename = temp;

   std::ifstream file;
   file.open(filename);

   /* doing things with file */

   file.close()
}


(Apologies if the code is not very well written; I haven't picked up many good programming practices.)

Anyway, my question is, why wouldn't the following code work?

1
2
3
4
5
6
7
8
9
10
11
12
13
void open_file(int id) {
   std::stringstream stream;
   stream << "file" << id << ".txt";
   char *filename;
   stream >> filename;

   std::ifstream file;
   file.open(filename);

   /* doing things with file */

   file.close()
}


Because when I try that, it simply quits upon trying to open the file. It seems strange to me that I need to use a temporary char as I did in the first bit of code.

EDIT: on further investigation, it seems it doesn't quit when opening the file, rather it quits when the function open_file is finished. That confuses me even more.
Last edited on
Both approaches are problematic.

Both temp and filename are just pointers. You never
reserve memory to hold the text you have in stream.

stream >> temp and stream >> filename overwrite
important stuff for your program, which is not good.

The fact that the first one works doesn't
mean it's safe. It could crash any time.

You can do what you want like this:

1
2
3
4
5
6
7
8
9
10
11
void open_file(int id) {
   std::stringstream stream;
   stream << "file" << id << ".txt";

   std::ifstream file;
   file.open(stream.str().c_str());

   /* doing things with file */

   file.close()
}
Last edited on
That works perfectly. Thanks!
Topic archived. No new replies allowed.