查找文件是否存在,文件属性、日期、大小;

1.判断文件是否存在

利用CFile类和CFileStatus类判断

CFileStatus filestatus;
if (CFile::GetStatus(_T("d:\\softist.txt"), filestatus))
    AfxMessageBox(_T("文件存在"));
else
    AfxMessageBox(_T("文件不存在"));

利用CFileFind类判断

CFileFind filefind;
CString strPathname = _T("d:\\softist.txt");
if(filefind.FindFile(strPathname))
    AfxMessageBox(_T("文件存在"));
else
    AfxMessageBox(_T("文件不存在"));

利用API函数FindFirstFile判断,这个函数还可以判断文件属性,日期,大小等属性。例:

WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(_T("d:\\softist.txt"), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) 
{
    AfxMessageBox(_T("文件不存在"));
} 
else 
{
    AfxMessageBox(_T("文件存在"));
    FindClose(hFind);
}

2.文件日期操作。下面是取得"d:\\softist.txt"的文件修改时间,TRACE以后,再把文件修改时间改成 2000-12-03 12:34:56

HANDLE     hFile;
FILETIME   filetime;
FILETIME   localtime;
SYSTEMTIME systemtime;

hFile = CreateFile(_T("d:\\softist.txt"), GENERIC_READ | GENERIC_WRITE,
					0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile != INVALID_HANDLE_VALUE) 
{
    GetFileTime(hFile, NULL, NULL, &filetime);      //取得UTC文件时间
    FileTimeToLocalFileTime(&filetime, &localtime); //换成本地时间
    FileTimeToSystemTime(&localtime, &systemtime);  //换成系统时间格式

    TRACE("%04d-%02d-%02d %02d:%02d:%02d\r\n",
          systemtime.wYear, systemtime.wMonth, systemtime.wDay,
          systemtime.wHour, systemtime.wMinute, systemtime.wSecond);

    //把文件时间修改成 2000-12-03 12:34:56
    systemtime.wYear = 2000; systemtime.wMonth = 12; systemtime.wDay = 3;
    systemtime.wHour = 12; systemtime.wMinute = 34; systemtime.wSecond = 56;
    SystemTimeToFileTime(&systemtime, &localtime);	//换成文件时间格式
    LocalFileTimeToFileTime(&localtime, &filetime);	//换成UTC时间
    SetFileTime(hFile, NULL, NULL, &filetime);		//设定UTC文件时间
    CloseHandle(hFile);
}

3.设置文件属性

BOOL SetFileAttributes( LPCTSTR lpFileName, DWORD dwFileAttributes );

dwFileAttributes 的意义
FILE_ATTRIBUTE_ARCHIVE   保存文件

FILE_ATTRIBUTE_HIDDEN    隐藏文件
FILE_ATTRIBUTE_NORMAL   通常文件
FILE_ATTRIBUTE_READONLY 只读文件
FILE_ATTRIBUTE_SYSTEM   系统文件

例:

SetFileAttributes(_T("d:\\softist.txt", FILE_ATTRIBUTE_READONLY);

 

 

posted @ 2013-06-26 10:00  友琼  阅读(620)  评论(0编辑  收藏  举报