Natalie Carr
Natalie Carr

Reputation: 3797

C string replacing backslashes

I currently using C string headers and C++ and have hit a problem. I have a long path:

C:\bla\bla\bla\bla

I need to change the backslashes to double backslashes so that my OS_CopyFile() function can read it properly but I don't know how?

I get my path using:

CHAR* szValueBuf = NULL;
DWORD cchValueBuf = 0;
UINT uiStat =  MsiGetProperty(hInstall, TEXT("OriginalDatabase"), TEXT(""), &cchValueBuf);

if (ERROR_MORE_DATA == uiStat)
{
    ++cchValueBuf; 
    szValueBuf = new TCHAR[cchValueBuf];
    if (szValueBuf)
    {
        uiStat = MsiGetProperty(hInstall, TEXT("OriginalDatabase"), szValueBuf, &cchValueBuf);
    }
}
if (ERROR_SUCCESS != uiStat)
{
    if (szValueBuf != NULL) 
        delete[] szValueBuf;
    return ERROR_INSTALL_FAILURE;
}

Upvotes: 0

Views: 2199

Answers (3)

john
john

Reputation: 87959

You have misunderstood how backslashes work in C++. Your string only has single backslashes. In a string literal you must use two backslashes in your code to get one backslash in the string at runtime.

OS_CopyFile(szValueBuf, "C:\\TEMP\\product.ini",0);

There are only two backslashes in the string above. You've invented for yourself a problem that doesn't exist.

Upvotes: 0

unwind
unwind

Reputation: 399843

If you have the string you show in a C variable at runtime, there's no risk that the backslashes will be changed.

Backslashes in C strings are only special to the C compiler while parsing source code, it will replace e.g. "\n" with a string that contains the single linefeed character. This replacement only happens in actual string literals, never in memory at run-time.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

Why not copy the original string, one character at a time, and when you see a backslash then you just append an extra backslash to the copy?

But as other has noted, if the string is not e.g. hardcoded in the source, then you most likely won't need to do this.

Upvotes: 1

Related Questions