共用方式為


擷取和變更檔案屬性

應用程式可以使用 GetFileAttributesGetFileAttributesEx 函式來擷取檔案屬性。 CreateFileSetFileAttributes 函式可以設定許多屬性。 不過,應用程式無法設定所有屬性。

本主題中的程式代碼範例會使用 CopyFile 函式,將目前目錄中的所有文本檔 (.txt) 複製到唯讀檔案的新目錄。 視需要,新目錄中的檔案會變更為唯讀。

應用程式會使用 CreateDirectory 函式,建立指定為參數的目錄。 目錄不能已經存在。

應用程式會使用 FindFirstFileFindNextFile 函式來搜尋目前目錄的所有文字檔。 每個文字文件都會複製到 \TextRO 目錄。 複製檔案之後,GetFileAttributes 函式會判斷檔案是否為唯讀。 如果檔案不是只讀的,應用程式會將目錄變更為 \TextRO,並使用 SetFileAttributes 函式,將複製的檔案轉換成只讀。

複製目前目錄中的所有文本文件之後,應用程式會使用 FindClose 函式關閉搜尋句柄。

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

void _tmain(int argc, TCHAR* argv[])
{
   WIN32_FIND_DATA FileData;
   HANDLE          hSearch;
   DWORD           dwAttrs;
   TCHAR           szNewPath[MAX_PATH];   
 
   BOOL            fFinished = FALSE; 

   if(argc != 2)
   {
      _tprintf(TEXT("Usage: %s <dir>\n"), argv[0]);
      return;
   }
 
// Create a new directory. 
 
   if (!CreateDirectory(argv[1], NULL)) 
   { 
      printf("CreateDirectory failed (%d)\n", GetLastError()); 
      return;
   } 
 
// Start searching for text files in the current directory. 
 
   hSearch = FindFirstFile(TEXT("*.txt"), &FileData); 
   if (hSearch == INVALID_HANDLE_VALUE) 
   { 
      printf("No text files found.\n"); 
      return;
   } 
 
// Copy each .TXT file to the new directory 
// and change it to read only, if not already. 
 
   while (!fFinished) 
   { 
      StringCchPrintf(szNewPath, sizeof(szNewPath)/sizeof(szNewPath[0]), TEXT("%s\\%s"), argv[1], FileData.cFileName);

      if (CopyFile(FileData.cFileName, szNewPath, FALSE))
      { 
         dwAttrs = GetFileAttributes(FileData.cFileName); 
         if (dwAttrs==INVALID_FILE_ATTRIBUTES) return; 

         if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) 
         { 
            SetFileAttributes(szNewPath, 
                dwAttrs | FILE_ATTRIBUTE_READONLY); 
         } 
      } 
      else 
      { 
         printf("Could not copy file.\n"); 
         return;
      } 
 
      if (!FindNextFile(hSearch, &FileData)) 
      {
         if (GetLastError() == ERROR_NO_MORE_FILES) 
         { 
            _tprintf(TEXT("Copied *.txt to %s\n"), argv[1]); 
            fFinished = TRUE; 
         } 
         else 
         { 
            printf("Could not find next file.\n"); 
            return;
         } 
      }
   } 
 
// Close the search handle. 
 
   FindClose(hSearch);
}

檔案屬性常數

檔名、路徑和命名空間