-
simple File I/O question
Hello
Below is a piece of code that opens a file.
if I got readFile(fileName) where "fileName" is a string containing a file the program does not compile.
Code:
string fileName;
fileName = "blah.txt";
ifstream readFile;
readFile.open(fileName);
Code:
ifstream readFile;
readFile.open("blah.txt");
if I enter the file name directly in quotes it works. How do I specify the file I want to open using a variable?
I've of course #include 'ed string and fstream
-
Try
readFile.open( fileName.c_str() );
-
thanks, just found out myself, learn the whole s string part and was a about to reply that I found a solution!
Good to see I was on the right track
-
Code:
readFile.open( fileName.c_str() );
what does the .c_str() do?
-
c_str()
The c_str() and data() methods of the string class, returns the string as an array of bytes, like "old" C strings.
string s = "Hello";
char *oldtypestring = s.c_str();
oldtypestring is now "Hello\0"