티스토리 툴바

블로그 이미지

Passion of ComputerScience

Team Blog For Soft Engineering Team Project Manager : Park, Choi, Jeon Project Name : Linkube (Link + cube) "Passion is survival, not death." by cocy


[api-스크랩] FindFirstFile


Console과 API의 경우에는 FindFirstFile과 FindNextFile을 이용하실 수 있습니다.

FindFirstFile의 원형은 다음과 같습니다.

HANDLE FindFirstFile(
  LPCTSTR
lpFileName // pointer to name of file to search for
  LPWIN32_FIND_DATA lpFindFileData
                       // pointer to returned information
);

 

lpFileName : 파일 검색을 위한 파일 이름. "c\\*.*"또는 "c:\\*.txt" 같은 형식을 지정할 수 있다.

lpFindFileData : 파일 검색용 데이터 구조체다. 검색된 파일들의 정보가 담겨진다.

 

두번째로 FindNextFile의 원형은 다음과 같습니다.

 

BOOL FindNextFile(
  HANDLE hFindFile,
  LPWIN32_FIND_DATA lpFindFileData
);

hFindFile : FindFirstFile이 넘겨준 핸들을 넣는다. 실제 검색용 스레드가 돌고 있는 핸들이다.

lpFindFileData : 파일 검색용 구조체. FindFirstFile이 넘겨준 구조체를 주면 된다.

 

세번째로 그 파일의 정보를 담는 WIN32_FIND_DATA입니다.

 

typedef struct _WIN32_FIND_DATA {
  DWORD dwFileAttributes;
  FILETIME ftCreationTime;
  FILETIME ftLastAccessTime;
  FILETIME ftLastWriteTime;
  DWORD nFileSizeHigh;
  DWORD nFileSizeLow;
  DWORD dwReserved0;
  DWORD dwReserved1;
  TCHAR cFileName[MAX_PATH];
  TCHAR cAlternateFileName[14];
} WIN32_FIND_DATA,
*PWIN32_FIND_DATA;

 

 

위의 두 함수를 조합하여 사용 할 수 있습니다.

 

아래는 MSDN에서 제공하는 예제소스입니다.

 

#define _WIN32_WINNT 0x0501

#include <windows.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
   WIN32_FIND_DATA FindFileData;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   char DirSpec[MAX_PATH];  // directory specification
   DWORD dwError;

   printf ("Target directory is %s.\n", argv[1]);
   strncpy (DirSpec, argv[1], strlen(argv[1])+1);
   strncat (DirSpec, "\\*", 3);

   hFind = FindFirstFile(DirSpec, &FindFileData);

   if (hFind == INVALID_HANDLE_VALUE) 
   {
      printf ("Invalid file handle. Error is %u\n", GetLastError());
      return (-1);
   } 
   else 
   {
      printf ("First file name is %s\n", FindFileData.cFileName);
      while (FindNextFile(hFind, &FindFileData) != 0) 
      {
         printf ("Next file name is %s\n", FindFileData.cFileName);
      }
    
      dwError = GetLastError();
      FindClose(hFind);
      if (dwError != ERROR_NO_MORE_FILES) 
      {
         printf ("FindNextFile error. Error is %u\n", dwError);
         return (-1);
      }
   }
   return (0);
}

소스는 간단합니다. FindFirstFile함수를 통해 디렉토리의 지정및 그 디렉토리의
가장 처음 파일을 찾습니다.
그후 FindNextFile을 통해 다음 파일들을 일일이 찾아서 검색조건에 일치한다면
TRUE를 리턴하는 것입니다.
WIN32_FIND_DATA 구조체에는 파일의 서치 정보가 들어있습니다. 파일의 속성및
파일이름, 생성날짜, 크기 등등 거의 모든 정보가 들어있습니다. 이를 활용하여
파일의 변경여부등도 파악이 가능합니다.
Comment 0 Trackback 0

Trackback : http://sepoc.tistory.com/trackback/51 관련글 쓰기

Top

prev 1 2 3 4 5 6 7 ... 41 next