By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,302 Members | 1,453 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,302 IT Pros & Developers. It's quick & easy.

Help with fstream.open();

P: 23
I'm a newbie at manipulating external files. Is there any way to specify a path to the file with C++? It thinks that the path in the file name string is filled with unrecognisable escape sequences. Here is the code for what I have so far:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5. int main()
  6. {
  7. fstream filestream("test.txt");
  8. string test = "test successful!";
  9. filestream << test;
  10. filestream.close();
  11. return 0;
  12. }
What's weird is that I created a text document of the same name in the same directory of the executable, yet when it runs it doesn't put anything into it, hence the want to know if I can specify a file path.
Mar 20 '07 #1
Share this Question
Share on Google+
1 Reply


Ganon11
Expert 2.5K+
P: 3,652
When using the general class fstream, you may have to specify that you want to use the file for output by including the ios::out value after the filename in the open command i.e.

Expand|Select|Wrap|Line Numbers
  1. filestream.open("test.txt", ios::out);
I haven't used fstream (instead I use ifstream and ofstream, more specific versions of fstream, which you may want to explore), so I'm not sure if this is correct.

As far as specifying the filepath, I assume you tried to open something like

Expand|Select|Wrap|Line Numbers
  1. filestream.open("C:\My Documents\Programming Stuff\test.txt");
at which point the compiler would complain about not recogning '\M' or '\P'. Simply replace each '\' by '\\' - the example would become:

Expand|Select|Wrap|Line Numbers
  1. filestream.open("C:\\My Documents\\Programming Stuff\\test.txt");
The escape character for a single backslash is two backslashes - if you don't include this in the filename, your compiler will think you are trying to make escape sequences rather than making a filename.
Mar 21 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.