向此代码添加NULL [英] Adding NULL To This Code
问题描述
此函数返回目录中的文件计数......但是,如果文件不存在,该函数将中断.我如何在其中添加NULL以不覆盖所需类型的文件.如果找不到文件,我希望它返回0.
This function is returning a count of files in the directory.....However If the file doesn''t exsist the function breaks. How can I add NULL to this to cover no files of the type desired. I want it to return 0 if no files are found.
int count = GetFileList(L"C:\\Users\\DS\\Downloads\\*.pdf", map);
函数本身.
The function itself.
int GetFileList(const wchar_t *searchkey, std::map &map)
抱歉,这是整个代码.
My apologies, here is the entire code.
struct file_data
{
std::wstring sLastAccessTime;
__int64 nFileSize ;
};
int GetFileList(const wchar_t *searchkey, std::map &map)
{
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFile(searchkey,&fd);
if(h == INVALID_HANDLE_VALUE)
{
return 0; // no files found
}
while(1)
{
wchar_t buf[128];
FILETIME ft = fd.ftLastWriteTime;
SYSTEMTIME sysTime;
FileTimeToSystemTime(&ft, &sysTime);
wsprintf(buf, L"%d-%02d-%02d",sysTime.wYear, sysTime.wMonth, sysTime.wDay);
file_data filedata;
filedata.sLastAccessTime= buf;
filedata.nFileSize = (((__int64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow;
map[fd.cFileName]= filedata;
if (FindNextFile(h, &fd) == FALSE)
break;
}
return map.size();
}
int main()
{
#define NULL 0;
std::map map;
int count = GetFileList(L"C:\\Users\\DS\\Downloads\\*.pdf", map);
int count1 = GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map);
int count2 = GetFileList(L"C:\\Users\\DS\\Downloads\\*.jpg", map);
for(std::map::const_iterator it = map.begin();
it != map.end(); ++it)
{
if (count != 0)
{
printf("\n Delete: %i \n", count);
}
else
{
printf ("%s \n", "Nothing");
}
system("pause");
return 0;
}
}
推荐答案
我希望它如果找不到文件,则返回0.
I want it to return 0 if no files are found.
此代码已经确保没有文件返回时返回0.
This code already ensure 0 is returned when no files are returned.
if(h == INVALID_HANDLE_VALUE)
{
return 0; // no files found
}
在for
循环中使用map
之前,应更改main()
以检查找到的文件数.
试试这个:
You should change your main()
to check for the number of found files before using the map
in the for
loop.
Try this:
GetFileList(L"C:\\Users\\DS\\Downloads\\*.pdf", map);
GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map);
GetFileList(L"C:\\Users\\DS\\Downloads\\*.jpg", map);
if( map.size() > 0 )
{
for(std::map::const_iterator it = map.begin(); it != map.end(); ++it)
{
....
}
}
同样,您还需要在GetFileList
函数返回之前关闭查找句柄.
在return map.size();
Also you need to close the find handle before the GetFileList
functions returns.
Add FindClose(h);
before return map.size();
Er前面添加FindClose(h);
,也许您会想编辑问题,以便它实际上包含所讨论的函数,而不是(不完整的)定义呢?只是一个想法...
Er, ahrm - perhaps you''d care to edit the question so that it actually includes the function in question, rather than an (incomplete) definition of it? Just a thought...
这篇关于向此代码添加NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!