Qt+VS 开发环境,设置程序当前路径 调用 Windows 的 SetCurrentDirectory 接口 总是失败。
示例代码如下,后面注释 是执行结果。
bool ret1 = SetCurrentDirectory("./print"); // false
bool ret2 = SetCurrentDirectory(".\\print"); // false
bool ret3 = SetCurrentDirectory("E:\DirPathTest\main\MyDemoQtProject\x64\Debug\print"); // false
bool ret4 = SetCurrentDirectory("E:\\DirPathTest\\main\\MyDemoQtProject\\x64\\Debug\\print"); // true
bool ret5 = SetCurrentDirectory("E:/DirPathTest/main/MyDemoQtProject/x64/Debug/print"); // true
QString strPath = QDir::currentPath() + "/print";
int len01 = (strPath.size()); // 57
int nSize01 = sizeof(strPath); // 8
QChar* pQChar = strPath.data();
//int len02 = strlen(pQChar);
int nSize02 = sizeof(pQChar); // 8
const char* path = "E:/DirPathTest/main/MyDemoQtProject/x64/Debug/print";
int len0 = strlen(path); // 51
int nSize0 = sizeof(path); // 8
bool ret6 = SetCurrentDirectory(path); // true
std::string str2 = strPath.toStdString();
int len03 = strlen(str2.data()); // 57
int len04 = str2.size(); // 57
int nSize03 = sizeof(str2); // 40
int nSize04 = sizeof(str2.data()); // 8
const char* arrPath = str2.c_str(); //
int len05 = strlen(arrPath); //57
int nSize05 = sizeof(arrPath); //8
bool ret7 = SetCurrentDirectory((arrPath)); // false
LPCSTR lpPathName = str2.c_str(); // (LPCSTR);
int len06 = strlen(lpPathName); // 57
int nSize06 = sizeof(lpPathName); // 8
bool ret8 = SetCurrentDirectory(lpPathName); // false
LPCTSTR lpPathName2 = (LPCTSTR)(str2.c_str());
int len07 = strlen(lpPathName2); // 57
int nSize07 = sizeof(arrPath); // 8
bool ret9 = SetCurrentDirectory(lpPathName2); // false
char dirPath[MAX_PATH] = {0};
GetCurrentDirectory(MAX_PATH, dirPath); // #define MAX_PATH 260
int len08 = strlen(dirPath); // 51
int nSize08 = sizeof(dirPath); // 260
bool ret10 = SetCurrentDirectory(dirPath); // true
QDir::currentPath() 获取路径长度为 57,比实际长度多了6个字符,说明QDir::currentPath() 获取的路径已经添加了转义字符,在vs中Debug调试看不到转义字符,导致调用 SetCurrentDirectory 一直失败