为什么 ShellExecute 不能使用包含文件路径的 LPCSTR 变量?

Why does ShellExecute not work with LPCSTR variable containing file path?

每天研究整周(从上周一,2016-05-30),测试各种 "solutions" 并构建程序数百次后,我终于设法编写了这段代码,它没有抛出任何错误或警告并且 应该 在 main.cpp 文件夹中找到 .txt 文件路径,成功地将反斜杠替换为正斜杠并打开准备编辑的文本文件。

在使用 LPCSTR 编写部分之前,当我尝试在 ShellExecute() 中使用字符串变量 path 而不是手动编写路径时抛出错误:

cannot convert 'std::string {aka std::basic_string<char>}' to 'LPCSTR {aka const char*}' for argument '3' to 'HISTANCE__* ShellExecuteA(HWND, LPCSTR, LPCSTR... [文档]

现在它可以找到路径并完美替换斜线,但不会打开 .txt 文件。

此外,我已经测试了函数 CreateProcess() 但我只能打开(在代码中手动编写路径).exe 文件,而不是 .txt。当我尝试使用其中的字符串变量调用函数时(第一个参数,应该是 LPCSTR),我得到了同样的错误,然后做了同样的解决方案(对于错误),如此处所示并且 CreateProcess() 没有打开 .exe 文件(例如,notepad.exe)。

我使用GNU GCC编译器,电脑OS是32位的,Windows.

编辑:通过在 GetFullPathName():

中将 .txt 添加到 "Text" 解决了问题(感谢 Andy)

GetFullPathName("Text.txt", 256, szDir, &fileExt);

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shellapi.h>
#include <stdio.h>
#include <cstring>

using namespace std;

string path; //global variable

void FindFilePath()
{
    char szDir[256], buffer[256];
    char* fileExt;
    GetFullPathName("Text", 256, szDir, &fileExt);
    snprintf(buffer, 256, "\"%s\"", szDir); //EDIT: quotes aren't necessary
    path = buffer;
    string find("\"), insert("/");
    int found = path.find(find);
    while (found >= 0) {
        if (found >= 0)
            path.replace(found, find.size(), insert);
        found = path.find(find);
    }
    /*
    If path.find(find) didn't find required symbol, for example,
    when string ends, it returns -1 and consequently terminates with
    an error 'std::length_error'.
    EDIT: replacing isn't necessary.
    */
    LPCSTR path2;
    {
        path2 = path.c_str();
        ShellExecute(GetDesktopWindow(), "edit", path2, NULL, NULL, SW_SHOW);
        cout << "TEST path2:\n" << path2 << endl;
    }
}

int main()
{
    ofstream REtext("Text.txt");
    REtext.close();
    //Created (so that program could find path) or
    //restarted text file (so that user had an empty file) in main.cpp folder.
    FindFilePath();
    cout << "\nPath is: " << path;

    return 0;
}

问题是 GetFullPathName() 没有 return 文件的完整路径,因为只提供了文件名,没有提供扩展名。添加扩展名后,它将 return 文件的绝对路径并且 ShellExecute() 将能够打开它。