我在读取 ASCII 字符的文件路径时没有问题,但在读取 Unicode 字符的文件路径时遇到问题。我试图确保代码正确编码以支持 unicode 字符,但它仍然不起作用。如何读取带有unicode字符或符号的文件和文件夹的路径?
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <string>
#include <vector>
#include <queue>
// Function to list files in BFS order
void ListFilesBFS(const std::wstring& inputDirectoryPath, std::wofstream& out) {
std::queue<std::wstring> pathsQueue;
pathsQueue.push(inputDirectoryPath);
// Loop until all directories have been processed
while (!pathsQueue.empty()) {
// Get the current directory path from the front of the queue
std::wstring currentPath = pathsQueue.front();
pathsQueue.pop();
// Find the first file or directory in the current directory
WIN32_FIND_DATAW findFileData;
HANDLE hFind = FindFirstFileW((currentPath + L"\\*").c_str(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE) {
// If unable to traverse the directory, print error and continue to next iteration
std::wcerr << L"Error traversing directory: " << currentPath << std::endl;
continue;
}
// Iterate through all files and directories in the current directory
do {
// Get the name of the file or directory
std::wstring fileName = findFileData.cFileName;
// Ignore '.' and '..' directories
if (fileName != L"." && fileName != L"..") {
// Construct the full path of the file or directory
std::wstring fullPath = currentPath + L"\\" + fileName;
// Construct the string containing file information
std::wstring fileInfo = fullPath;
// Write the file information string to the output file stream
out << fileInfo << std::endl;
// If it's a directory, add it to the queue for further traversal
if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
pathsQueue.push(fullPath);
}
}
} while (FindNextFileW(hFind, &findFileData) != 0);
// Close the handle to the directory
FindClose(hFind);
}
}
// Entry point of the program
int wmain(int argc, wchar_t* argv[]) {
// command-line argument: "lister.exe <input_directory_path> <output_file_path>"
// Get the input directory path and output file path
std::wstring inputDirectoryPath = argv[2];
std::wstring outputFile = argv[3];
// Open the output file
std::wofstream out(outputFile);
if (!out.is_open()) {
std::wcerr << L"Unable to open output file." << std::endl;
return 1;
}
// Call ListFilesBFS function to list files in BFS order
ListFilesBFS(inputDirectoryPath, out);
// Close the output file
out.close();
return 0;
}
您需要设置输出模式来处理 Windows UTF-16 字符:
#include <fcntl.h>
#include <io.h>
..
main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stderr), _O_U16TEXT);
...