Duppy
Duppy

Reputation: 1

C++ : Escaping quotes for std::string behaves differently on Linux vs Windows

So , my problem seemed an easy one to begin with. I'm interested in saving the exact cmd line arguments i'm receiving in the main() of my program because of some inherited code that i'm supposed to use that needs access to it but gets called further down inside the code. I won't get into more detail here.

The main problem is the fact that if i pass a path that contains spaces, that path needs to be placed between double quotes. Those double quotes get stripped away by argv[] so i need to add them back.

So i did something like the following:

string buff;
buff.assign("");
for(int i = 0; i < m_argc; i++)
{
    buff.append("\"");
    buff.append(m_argv[i]);
    buff.append("\" ");            
}

Which on WINDOWS returns what i expect, something like this :

"C:\...\myProg.exe" "-s" "-i" "c:\...\file with spaces.dat".

Which is what i expect.

On LINUX, however i get something like this:

\"/.../myProg.exe\" \"-s\" \"-i\" \"/.../file with spaces.dat\"

Which is completely unexpected to me and further messes up any processing thereafter

Any help is appreciated, thanks :)

EDIT, as requested , a working example:

#include <iostream>
#include <cstdio>
#include <string.h>
#include <stdlib.h>    

int main(int argc, char* argv[], char* envp[])
{
    int nRetCode = 0;

    std::string buff;
    buff.assign("");

    for(int i = 0; i < argc; i++)
    {
        if (i != argc-1)
        {
            if (i > 0 && (strcmp(argv[i-1],"-i") == 0 || strcmp(argv[i-1],"-o") == 0))
            {
                buff.append("\"");
                buff.append(argv[i]);
                buff.append("\" ");
            }
            else
            {
                buff.append(argv[i]);
                buff.append(" ");
            }
        }
        else
        {
            if (i > 0 && (strcmp(argv[i-1],"-i") == 0 || strcmp(argv[i-1],"-o") == 0))
            {
                buff.append("\"");
                buff.append(argv[i]);
                buff.append("\"");
            }
            else
                buff.append(argv[i]);
        }
    }

    std::cout << "contents of buff: \n" << buff.c_str() << std::endl;

    return nRetCode;
}

I get a correct output from this one:

/.../myProg -s -i "/.../file with spaces"

As PaulMcKenzie and Igor Tandetnik suggested, that's just how the debugger reports the contents of the string.

Thank you for the help, everyone

Upvotes: 0

Views: 197

Answers (1)

Aganju
Aganju

Reputation: 6395

The linux OS uses / for directory paths; Windows uses \. Nothing you can do about that.

The OS simply delivers all paths to you the way it knows them.

Upvotes: 1

Related Questions