Pregunta

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?

¿Fue útil?

Solución

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;
}

Otros consejos

Your GetFiles function is returning a pointer to memory which is no longer valid, File_Data.cFileName can only be used in GetFiles because that's where File_Data is defined. The simplest solution is to use the C++ string classstd::string.

std::string GetFiles(LPCSTR path)
{
    WIN32_FIND_DATA File_Data; 
    LPCSTR lPath = mergeString(path,"\\*.txt");
    FindFirstFile(lPath, &File_Data);
    return File_Data.cFileName;
}

Using pointers unnecessarily is a bad habit to get into, for this kind of reason (any many more).

Your mergeString function should also be rewritten with fewer pointers.

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

    convertedString.insert(i, secondString);
    return convertedString;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top