0
votes

I've spent many hours on here looking for help on what is apparently a common error but none that I've seen seems to fit my case.

I am migrating a old out sourced program that was written in Visual Studio 6 C++ to Visual Studio 2012 and fortunately for me as I'm not a C++ programmer (just a lowly VB and C# developer). The migration wizard and the internet have been a great help in helping me find and correct code that the wizard can't handle.

In this code block which I believe is doing nothing more than creating a directory

int CreateAllDirectories(const char* pszDir)
{
char*   pszLastSlash;
char    cTmp;


if( _access( pszDir, 0 ) != -1 ) {
    // it already exists
    return 0;
}

pszLastSlash = strrchr( pszDir, '\\' );
if ( pszLastSlash ) {
    cTmp = *pszLastSlash;
    *pszLastSlash = '\0';

    // try again with one less dir
    CreateAllDirectories( pszDir ); 

    *pszLastSlash = cTmp;
}

if ( _mkdir( pszDir ) == -1 ) {
    return -1;
}

return 0;

}

an error generates when the results of strrchr( pszDir, '\' ) are assigned to the variable pszLastSlash. From the rest of this code it looks like pszLastSlash = strrchr( pszDir, '\' ); is a valid expression.

Is the issue with the double backslash which to me looks like and escape sequence.

3

3 Answers

3
votes

Maybe in this line...

pszLastSlash = strrchr( pszDir, '\\' );

pszLastSlash is not constant but pszDir is constant. There are two defs for strrchr() (see http://www.cplusplus.com/reference/cstring/strchr/)...

const char * strchr ( const char * str, int character );
      char * strchr (       char * str, int character );

Because you input a constant char *, it will try to use the def that returns a const char*, but you're assigning it to a non-const char*. I think that is what is generating your error.

Because pszDir is const, the pointer returned to you is const because you shouldn't be modifying the area of memory pointed to by pszDir.

If you have allocated pszDir yourself, and you know it is safe to modify, your could relax your const contraint in the function def? I.e.,

int CreateAllDirectories(char* pszDir)

But, only do this is pszDir is a string that you own and can modify :)

I just noticed in the C++ reference page that...

In C, this function is only declared as:
    char * strchr ( const char *, int ); 

So, if you previously used C, then that would explain why you see the error now.

0
votes

Since this line

*pszLastSlash = '\0';

is modifying the buffer passed into your function, you must not promise your caller that you won't modify the buffer. Therefore

int CreateAllDirectories(char* pszDir);

is the correct signature

0
votes

You can try putting new in the middle of

pszLastSlash = strrchr( pszDir, '\' );

So, it will be

:pszLastSlash = new strrchr( pszDir, '\' );