现在的位置: 首页 > 综合 > 正文

VC MFC 修改目录时间方法

2013年05月04日 ⁄ 综合 ⁄ 共 2463字 ⁄ 字号 评论关闭
// 修改指定目录的时间
BOOL SetDirTime(char DirName, SYSTEMTIME new_stime)   
{
  HANDLE hDir;
  // 打开目录的Win32 API调用
  // 必须“写”方式打开
  // 打开现存的目录
  // 只有这样才能打开目录
  hDir = CreateFile (   DirName,   GENERIC_READ | GENERIC_WRITE,    FILE_SHARE_READ|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,    FILE_FLAG_BACKUP_SEMANTICS,    NULL);
  if (hDir ==INVALID_HANDLE_VALUE ) return FALSE;
  // 打开失败时返回
  FILETIME lpCreationTime;
  // creation time目录的创建时间
        FILETIME lpLastAccessTime;
  // last access time最近一次访问目录的时间
  FILETIME lpLastWriteTime;
  // last write time最近一次修改目录的时间
     SystemTimeToFileTime(&new_stime, &lpCreationTime);
  // 转换成文件的时间格式
  SystemTimeToFileTime(&new_stime, &lpLastAccessTime);
  SystemTimeToFileTime(&new_stime, &lpLastWriteTime);
  // 修改目录时间的Win32 API函数调用
  BOOL retval = SetFileTime( hDir, &lpCreationTime,&lpLastAccessTime,&lpLastWriteTime);
    CloseHandle(hDir);
  // 关闭目录
  return retval;
  // 返回修改成功与否的返回码
       
}
// 获取指定目录的时间
BOOL GetDirTime(char DirName, SYSTEMTIME & stime)   
{
  HANDLE hDir;
  // 打开目录的Win32 API调用
  // 只需读方式打开即可
  // 打开现存的目录
  hDir = CreateFile ( DirName,  GENERIC_READ,    FILE_SHARE_READ|FILE_SHARE_DELETE, NULL, OPEN_EXISTING,    FILE_FLAG_BACKUP_SEMANTICS,NULL);
  FILETIME lpCreationTime;
  // creation time目录创建时间
  FILETIME lpLastAccessTime;
  // last access time目录最近访问时间
  FILETIME lpLastWriteTime;
  // last write time目录最近修改时间
  // 获取目录日期和时间的Win32 API调用
  BOOL retval = GetFileTime(    hDir,&lpCreationTime,&lpLastAccessTime &lpLastWriteTime);
  if ( retval ) 
  {
    FILETIME ftime;
    FileTimeToLocalFileTime(&lpLastWriteTime, &ftime);
    // 转换成本地时间
    FileTimeToSystemTime(&ftime, &stime) ;
    // 转换成系统时间格式}
    CloseHandle(hDir);
    return retval;
  }
}
int DoTest(char DirName)    
{
  SYSTEMTIME stime;
  printf(″testing for directory [%s]/n″, DirName) ;
  // 显示修改前目录的时间
  if ( GetDirTime(DirName, stime) )      
       printf(″before change is %04d-%02d-%02d %02d:%02d:%02d/n″, stime.wYear , stime.wMonth , stime.wDay , stime.wHour , stime.wMinute, stime.wSecond );
  else   
       printf(″failed to get the datetime of directory.../n″);
  stime.wYear = 1995;
  stime.wMonth = 5;
  stime.wDay = 12;
  stime.wHour = 10 - 8;
  // GMT time, GMT+8 for China PRC
  stime.wMinute = 11;
  stime.wSecond = 12;
  // GetSystemTime(&stime);
  // 如果要设置成当前的时间
  // 修改目录的时间
  if ( SetDirTime(DirName, stime) )    
      printf(″success to change datetime of directory./n″);
  else 
      printf(″failed to change the datetime of directory.../n″);
  // 显示修改后目录的时间
  if ( GetDirTime(DirName, stime) )    
     printf(″after change is %04d-%02d-%02d %02d:%02d:%02d/n″,stime.wYear , stime.wMonth , stime.wDay ,stime.wHour , stime.wMinute, stime.wSecond );
  else 
     printf(″failed to get the datetime of directory.../n″);
  return 0;
}
void main(int argc, char argv[])    
{
  DoTest(″c://dir″);
}

抱歉!评论已关闭.