[kaze's test] プログラミングメモ →目次

ファイルの属性

1.ファイルの存在の判断

CFileクラスとFileStatusクラスで判断します。

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);