0

I have some files with the type "File" I mean instead of "Resource\sample.txt", their name is "Resource\sample" Now I want to read them with c++ and store them in a string. Here is my code:

std::stringstream textBuffer;
std::fstream fileHandle;
std::string content
fileHandle.open("Resource\sample", std::ios::in);
textBuffer << fileHandle.rdbuf();
content = textBuffer.str();
fileHandle.close();

But when I compile this the value of "content" variable is equal to "". Help me on this . Thanks in Advance. Please note that the only problem is that the file has no extension such as .txt or .dat or .bin of whatsoever.

Pete Becker
  • 69,019
  • 6
  • 64
  • 147

1 Answers1

10

You did not properly escape the backslash in your filename string. You need to either escape the string:

fileHandle.open("Resource\\sample", std::ios::in);

or use a raw string literal:

fileHandle.open(R"(Resource\sample)", std::ios::in);
Werner Henze
  • 15,279
  • 12
  • 41
  • 62
  • Because if change the address to "Resource\sample.txt" and add the ".txt" extension to the file as well everything works properly. – E.Pajouheshgar Dec 17 '15 at 16:27
  • Backslash is an escape character, see http://stackoverflow.com/questions/10220401/c-string-literals-escape-character. A backslash means that the Compiler will not put a backslash into the string but a character that depends on what follows the backslash. A common escape sequence is '\n' for newline. "\s" will be reduced to "s". You can check that in a Debugger or with printf. – Werner Henze Dec 17 '15 at 16:28
  • 2
    My only Explanation why it succeeds when adding ".txt": you have a program that wrote this file. You did the same error and the file on disc is not "Resource\sample.txt" but "Resourcesample.txt" (and on disc you have "Resource\sample" but no "Resourcesample")!? – Werner Henze Dec 17 '15 at 16:31