# file stream using a variable and text

## Recommended Posts

I have a variable holding the name of a book i want to open but they are in a different folder named 'books' in my project directory, so i was wondering what i have to do to code this, can i do something like: std::fstream File(("books//")bookName); or should i concatanate the char* with the "books//", if so whats the best way to do this? NP: The name of the book changes but the 'books' folder doesnt is what im getting at. Thanks again, Mark

##### Share on other sites
#include <sstream>std::stringstream ss;ss << "books/" << bookName;std::string bookPath = ss.str();

##### Share on other sites
#include <sstream>std::stringstream ss;ss << "books/" << bookName;std::string bookPath = ss.str();

Whats the equivilent of that but for char* as fstream doesnt like strings :D

##### Share on other sites
I am pretty sure you can make it return a c string by doing this:

ss.str().c_str();

I'm not near a compiler at this time so I can't test it, but that should return a c style string.

##### Share on other sites
: error C2664: 'std::basic_fstream<_Elem,_Traits>::basic_fstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const char *'

still didnt like it :O

##### Share on other sites
#include <fstream>#include <string>char * bookName = "my_book.txt";std::fstream stream((std::string("books/") + bookName).c_str(), std::ios::in);

this should do the trick for you.

##### Share on other sites
Awesome thanks a bunch everyone.

##### Share on other sites
one final thing.. I would like my file stream to be able to open up files with the extention .ebr, its basically just a text file but renamed to something different. You might ask whats the point but for my final year project i said i was going to develop a file type even if only the internal structure was different, any ideas?

##### Share on other sites
The filename extension means absolutely Nothing. It says nothing about the content of the file whatsoever. You could name a file movie.wmv and the contents could be the text "haha, just kidding. This isn't really a movie". It's only after being interpreted that a file becomes meaningful. In the case of the movie.wmv file, if you tried opening it in, say, windows media player, it would look at the file and determine it is in the wrong format, probably because the first chunk of a wmv file is supposed to contain specific information.

In summary, just change your extension from .txt to .ebr and you're good to go.

##### Share on other sites
Ahh ok, i thought that much but when i tried it the code compiled but then gave an error in ioswd (IIRC) it might be to do with something else though.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627643
• Total Posts
2978362

• 10
• 12
• 22
• 13
• 33