SHFileOperation copying folders using strings

痞子三分冷 提交于 2019-12-05 18:34:08

The std::string does strlen (or similar) to find the end of the constant char array and allocates only the required number of characters. So it stops on the first null and does not copy the other one. If you want to override this, you need to use constructor that takes size, like:

string source("D:\\check\\folder4\\0", 18);

Note that the second null character is added automatically just as with any other string.

Or add the null character explicitly like (way better solution):

std::string source = std::string("D:\\check\\folder4") + std::string(1, '\0');

Or

std::string source = "D:\\check\\folder4";
source.append(1, '\0');

As for the other question, why using constant character array works:

I believe that, if it works, it just a pure luck that the byte/character in memory after the constant character array is null.

You can test this yourself (in debugger or by printing the values):

// this is the compiler generated null
(*(sf.pFrom + strlen(sf.pFrom))) == '\0'

// this is the following byte/character that should be luckily null
(*(sf.pFrom + strlen(sf.pFrom) + 1)) == '\0' 

If you find that the following character is not null in debugger, make sure you finish debugging until the SHFileOperationA. As in that particular case it can fail/crash/whatever (while it normally does not) as the fact you are debugging alone may make the memory image different.

Also you have not specified what you exactly mean by "it works". Do you mean result of SHFileOperationA (what is it). Or that the application crashes/throws, when it does not work. Or that the files are copied or not. This might help answering you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!