Reputation: 3
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
#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;
}
Upvotes: 0
Views: 86
Reputation: 3890
You cast strfile
to LPCTSTR
, and write the file stream of ofstream
, the character sets of the two do not match.
You can use wofstream
to solve this problem:
std::wofstream file;
Or use CT2A
function to convert it:
for (const auto& strFile : listFiles)
file << CT2A(strFile) << std::endl;
More reference : Convert CString to const char*
Upvotes: 1