【问题标题】:Redirection of a std::list<CString> content to a text file将 std::list<CString> 内容重定向到文本文件
【发布时间】:2021-04-02 14:29:18
【问题描述】:

我正在使用该代码枚举驱动器中具有特定扩展名的文件并将它们写入文本文件。 它在文本文件中输出类似这样的内容。我怎样才能用他们的名字而不是这些垃圾值来写文件地址。 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;
}

【问题讨论】:

    标签: c++ winapi std lpcstr


    【解决方案1】:

    你将strfile转换为LPCTSTR,写入ofstream的文件流,两者的字符集不匹配。

    你可以使用wofstream来解决这个问题:

    std::wofstream file;
    

    或者使用CT2A函数进行转换:

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

    更多参考:Convert CString to const char*

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2014-08-09
      相关资源
      最近更新 更多