这两天在写个遍历文件批处理的小工具,碰到几个时间相关的函数,整理了下,说不定以后可能会再用到呢~
//判断文件是否存在
bool FileIsExists(LPCSTR filePath)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(filePath, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
return false;
}
FindClose(hFind);
return true;
}
//获取文件最后修改时间距当前时间的差值(用于判断该文件是否正在写的一种方法)
time_t FileTimeToTime_t(FILETIME ft)
{
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
return ((LONGLONG)(ui.QuadPart - 116444736000000000) / 10000000);
}
time_t GetLastWriteTimeUntilNow(const std::string& fileName)
{
WIN32_FIND_DATA ffd ;
HANDLE hFind = FindFirstFile(fileName.c_str(),&ffd);
SYSTEMTIME stUTC, stLastWriteTime;
FileTimeToSystemTime(&(ffd.ftLastWriteTime), &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLastWriteTime);
SYSTEMTIME stCurrentTime;
GetLocalTime(&stCurrentTime);
FILETIME fTime1;
FILETIME fTime2
SystemTimeToFileTime(&stLastWriteTime,&fTime1);
SystemTimeToFileTime(&stCurrentTime,&fTime2);
return (FileTimeToTime_t(fTime2) - FileTimeToTime_t(fTime1));
}
//遍历文件夹
int DirectoryList(LPCSTR Path,std::string paramFormart)
{
WIN32_FIND_DATA FindData;
HANDLE hError;
int FileCount = 0;
char FilePathName[LEN];
// 构造路径
char FullPathName[LEN];
strcpy(FilePathName, Path);
strcat(FilePathName, "\\*.*");
hError = FindFirstFile(FilePathName, &FindData);
if (hError == INVALID_HANDLE_VALUE)
{
printf("搜索失败!");
return 0;
}
while(::FindNextFile(hError, &FindData))
{
// 过虑.和..
if (strcmp(FindData.cFileName, ".") == 0
|| strcmp(FindData.cFileName, "..") == 0 )
{
continue;
}
// 构造完整路径
wsprintf(FullPathName, "%s\\%s", Path,FindData.cFileName);
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
DirectoryList(FullPathName,paramFormart);
}
else
{
FileCount++;
//本级的文件;
std::string transformFile = FullPathName;
std::string fileSuffix = transformFile.substr(transformFile.size() - 3, transformFile.size());
std::string fileEnd = transformFile.substr(transformFile.size() - 7, transformFile.size());
transformFile += ".mp4";
if ( fileSuffix == "mp4" && fileEnd != "mp4.mp4" && !FileIsExists(transformFile.c_str()) )
{
time_t tTime = GetLastWriteTimeUntilNow(FullPathName);
if (tTime < 60 && tTime > -60)
{
printf("[%s] 修改60秒内不做变动,稍后再试!\n",FullPathName);
continue;
}
//FILE* fp = fopen(FullPathName, " a+");
//if(fp==NULL) //如果失败了
//{
// printf("[%s] 正在写,稍后再试!\n",FullPathName);
// continue;
//}
//对该文件做一些业务操作
printf("Transform file: %s \n", FullPathName);
HINSTANCE hNewExe = ShellExecuteA(NULL, "open", "ffmpeg.exe", param , NULL, SW_SHOW);
}
}
}
return 0;
}