Share via


파일 특성 가져오기 및 변경

애플리케이션은 GetFileAttributes 또는 GetFileAttributesEx 함수를 사용하여 파일 특성을 가져올 수 있습니다. 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);
}

파일 특성 상수

파일 이름, 경로 및 네임스페이스