Search code examples
c++windowsstringwinapilpcstr

FindFirstFile LPCSTR


Hello i got a problem with my code here.

LPCSTR mergeString(LPCSTR firstString, std::string secondString)
{
    string convertedString = ConvertString(firstString);
    LPCSTR mergedString;
    int i = convertedString.size();

    convertedString.insert(i, secondString);
    mergedString = (convertedString.c_str());

    return mergedString;
}

void GetFiles(LPCSTR path)
{
    WIN32_FIND_DATA File_Data; 
    LPCSTR lPath = mergeString(path,"\\*.txt");
    FindFirstFile(lPath, &File_Data);
    wcout << File_Data.cFileName;
}

You pass in the path you want to use in the GetFiles(LPCSTR path) Then i use the mergestring function to merge together the path with a extension (\*.txt) everything works except when it returns the LPCSTR then its just a lot of wierd characters and i dont know why or is it a better way to do this?


Solution

  • Your code is unnecessarily complicated. If you just want to add a \*.txt suffix to the input path string, you can simply use std::string with its overloaded operator+.

    Then, if you want to pass a std::string to a Win32 API that has a const char* (i.e. LPCSTR) parameter, you can use std::string::c_str() method:

    void GetFiles(LPCSTR path)
    {
        WIN32_FIND_DATA fileData; 
        std::string searchPath(path);
        searchPath += "\\*.txt";
    
        FindFirstFile(searchPath.c_str(), &fileData);
        wcout << fileData.cFileName;
    }
    

    Note also that in modern world you should use Unicode (UTF-16) for Win32 programming; so const wchar_t* and std::wstring are better options than const char* and std::string. Moreover, I'd just use a std::wstring class as parameter, instead of a raw wchar_t pointer.

    void GetFiles(const std::wstring& path)
    {
        std::wstring searchPath = path + L"\\*.txt";
        WIN32_FIND_DATA fileData; 
        FindFirstFile(searchPath.c_str(), &fileData);
        std::wcout << fileData.cFileName;
    }