2

This should be a fairly trivial problem. I'm trying to open an ofstream using a std::string (or std::wstring) and having problems getting this to work without a messy conversion.

std::string path = ".../file.txt";

ofstream output;

output.open(path);

Ideally I don't want to have to convert this by hand or involve c-style char pointers if there's a nicer way of doing this?

3 Answers 3

9

In the path string, use two dots instead of three.

Also you may use 'c_str()' method on string to get the underlying C string.

output.open(path.c_str());
Sign up to request clarification or add additional context in comments.

Comments

2

this should work:

output.open(path.c_str())

Comments

0

I'm afraid it's simply not possible. You have to use c_str, and yes, it sucks.

Incidentally, using char* also means fstream has no support for Unicode file names... a shame.

4 Comments

wfstream for std::wstring anyone?
No need for a special stream type, just overload open() to take a std::wstring.
basic_fstream's constructor accepts only const char * (never wchar_t). See the standard: 27.8.1.6
@Assaf - I know what is in the standard, I was replying to KTC's comment about making another stream class, which doesn't make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.