前言
设置vs的高级属性为使用多字节字符集
,不然会报char类型的实参与LPCWSTR类型的形参类型不兼容
的错误
代码
#include <iostream>
#include <cstring>
#include <windows.h>
void listFiles(const char* dir);
int main()
{
using namespace std;
char dir[100] = "D:/prostate_run/";
/*cout << "Enter a directory (ends with \'\\\'): ";
cin.getline(dir, 100);*/
strcat_s(dir, "*.*"); // 需要在目录后面加上*.*表示所有文件/目录
listFiles(dir);
return 0;
}
void listFiles(const char* dir)
{
using namespace std;
HANDLE hFind;
WIN32_FIND_DATA findData;
LARGE_INTEGER size;
hFind = FindFirstFile(dir, &findData);
if (hFind == INVALID_HANDLE_VALUE)
{
cout << "Failed to find first file!\n";
return;
}
do
{
// 忽略"."和".."两个结果
if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0)
continue;
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // 是否是目录
{
cout << findData.cFileName << "\t<dir>\n";
}
else
{
size.LowPart = findData.nFileSizeLow;
size.HighPart = findData.nFileSizeHigh;
cout << findData.cFileName << "\t" << size.QuadPart << " bytes\n";
}
} while (FindNextFile(hFind, &findData));
cout << "Done!\n";
}