简体   繁体   English

重定向 std::list<cstring> 内容到文本文件</cstring>

[英]Redirection of a std::list<CString> content to a text file

I am using that code to enumerate files with specific extensions in a drive and write them out to a text file.我正在使用该代码来枚举驱动器中具有特定扩展名的文件并将它们写入文本文件。 It outputs something like this in the text file.它在文本文件中输出类似这样的内容。 How can I write file address with their names instead of these garbage values .我怎样才能用他们的名字而不是这些垃圾值来写文件地址。 00000281BBACF338 00000281BBACEA78 00000281BBACF108 00000281BBAD1E48 00000281BBACF338 00000281BBACEA78 00000281BBACF108 00000281BBAD1E48

#include <Windows.h>
#include <atlpath.h>
#include <list>
#include <iostream>
#include <fstream>

#ifdef _UNICODE
#define cout wcout
#endif

void FindFiles(
    const CString& strRootPath,
    const CString& strExt,
    std::list<CString>& listFiles,
    bool bRecursive = true)
{
    CString strFileToFind = strRootPath;
    ATLPath::Append(CStrBuf(strFileToFind, MAX_PATH), _T("*.*"));

    WIN32_FIND_DATA findData = { 0 };
    HANDLE hFileFind = ::FindFirstFile(strFileToFind, &findData);
    if (INVALID_HANDLE_VALUE != hFileFind)
    {
        do
        {
            CString strFileName = findData.cFileName;
            if ((strFileName == _T(".")) || (strFileName == _T("..")))
                continue;

            CString strFilePath = strRootPath;
            ATLPath::Append(CStrBuf(strFilePath, MAX_PATH), strFileName);
            if (bRecursive && (ATLPath::IsDirectory(strFilePath)))
            {
                FindFiles(strFilePath, strExt, listFiles);
            }
            else
            {
                CString strFoundExt = ATLPath::FindExtension(strFilePath);
                if (!strExt.CompareNoCase(strFoundExt))
                    listFiles.push_back(strFilePath);
            }

        } while (::FindNextFile(hFileFind, &findData));

        ::FindClose(hFileFind);
    }
}

int main()
{
    std::ofstream file;
    file.open("test.txt", std::ios::out | std::ios::app | std::ios::binary);

    std::list<CString> listFiles;
    FindFiles(_T("D:\\"), _T(".txt"), listFiles);
    for (const auto& strFile : listFiles)
        file << (LPCTSTR)strFile.GetString() << std::endl;
    return 0;
}

You cast strfile to LPCTSTR , and write the file stream of ofstream , the character sets of the two do not match.您将strfileLPCTSTR ,并写入ofstream的文件 stream ,两者的字符集不匹配。

You can use wofstream to solve this problem:你可以使用wofstream来解决这个问题:

std::wofstream file;

Or use CT2A function to convert it:或者使用CT2A function 进行转换:

for (const auto& strFile : listFiles)
    file << CT2A(strFile) << std::endl;

More reference: Convert CString to const char*更多参考: 将 CString 转换为 const char*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM