检索和更改文件属性

应用程序可以使用 GetFileAttributes 或 GetFileAttributesEx 函数检索文件属性。 CreateFile 和 SetFileAttributes 函数可以设置许多属性。 但是,应用程序无法设置所有属性。

本主题中的代码示例使用 CopyFile 函数将当前目录中的所有文本文件 (.txt) 复制到只读文件的新目录。 如有必要,新目录中的文件将更改为只读。

应用程序使用 CreateDirectory 函数创建指定为参数的目录。 该目录不得已存在。

应用程序使用 FindFirstFile 和 FindNextFile 函数在当前目录中搜索所有文本文件。 每个文本文件都复制到 \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);
}

文件属性常量

文件名、路径和命名空间