1

I am trying to figure out this and its bugging me for a long now.

when i type:

inFile.open("C:\Users\Mark\Desktop\text.txt", ios::in | ios:: binary);

it works just fine. But when i do something like this.

string garbage = "\\";

        srcLoc = ofn.lpstrFile; // this is: C:\Users\Mark\Desktop\text.txt

        // This for loop inserts "\\"
        for(int i = 0; i < srcLoc.length(); i++)
        {
            switch(srcLoc[i])
            {
            case '\\':
                srcLoc.insert(i, garbage);
                i++;
                break;
            }
        }
       // Now string srcLoc looks like: C:\\Users\Mark\\Desktop\\text.txt
        inFile.open(srcLoc.c_str(), ios::in | ios:: binary);
       // But it wont work

        if(inFile)
        {
            while(!inFile.eof())
            {
                getline(inFile, tekst);
                SendMessage(hTextBox, EM_REPLACESEL, 0, (LPARAM)tekst.c_str());
                SendMessage(hTextBox, EM_REPLACESEL, 0, (LPARAM)"\r\n");
            }
        }
        else
        {
            MessageBox(0, srcLoc.c_str(), "Could not load", MB_ICONWARNING | MB_OK);
        }
        inFile.close();

What i get is MessageBox "Could not load" working at least :) Anyone know what i am missing?

Marko
  • 49
  • 1
  • 6
  • 2
    You should only need to double the backslashes in literal strings, not in variables that are already alright. – Some programmer dude Mar 28 '12 at 18:34
  • 1
    When you're hard coding a file path in a literal string just use a `/`, it works on Windows too and then you don't need to escape all the backslashes. – Praetorian Mar 28 '12 at 18:58

2 Answers2

6

You need to double the backslashes when you're using them in a string in source code. The compiler will convert each double-backslash in your source code to a single source code in the string used by the program. When you're reading a string coming in at run time, you do not need to double the backslashes.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1
// Now string srcLoc looks like: C:\\Users\Mark\\Desktop\\text.txt

This is not what the string should look like in the debugger (or anywhere else during runtime). This is only the way a string with backslashes is represented in source code.

Your loop attempting to add an extra '\' doesn't work either, because the compiler will remove the single backslashes and replace them with the value corresponding to the escape sequence, if any. For example the sequence '\t' is replaced by a tab character.

You can solve your problems by using an alternate path separator instead

"C:/Users/Mark/Desktop/text.txt"

this works for Windows as well, and not just for Linux.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203