순차적으로 파일을 복사하는 프로그램을 다음 세가지 방식으로 구현해보겠습니다.


1. 표준 C 라이브러리를 이용

2. Windows API 를 이용

3. Windows API 인 CopyFile 를 이용


1. 표준 C 라이브러리를 이용

 

#include <stdio.h>
#include <errno.h>

#define BUF_SIZE 256

int main (int argc, char *argv [])
{
FILE *inFile, *outFile;
char rec[BUF_SIZE];
size_t bytesIn, bytesOut;
if (argc != 3) {
  fprintf (stderr, "Usage: cp file1 file2\n");
  return 1;
}

inFile = fopen (argv[1], "rb");
if (inFile == NULL) {
  perror (argv[1]);
  return 2;
}
outFile = fopen (argv[2], "wb");
if (outFile == NULL) {
  perror (argv[2]);
  fclose(inFile);
  return 3;
}

while ((bytesIn = fread (rec, 1, BUF_SIZE, inFile)) > 0) {
  bytesOut = fwrite (rec, 1, bytesIn, outFile);
  if (bytesOut != bytesIn) {
   perror ("Fatal write error.");
   fclose(inFile);
   fclose(outFile);
   return 4;
  }
}

fclose (inFile);
fclose (outFile);
return 0;
} 

 

 

  1) perror 자체는 전역 변수 errno에 접근하여 함수 호출 실패에 대한 정보를 알아낸다.

  2) IO는 동기적(synchronous)이다. 연산이 끝날 때까지 기다렸다가 다음으로 나아간다.

  3) Windows 뿐만 아니라 다른 시스템에서도 실행이 가능하다.



2. Windows API 를 이용


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

#define BUF_SIZE 256 

int main (int argc, char * argv[])
{
 HANDLE hIn, hOut;
 DWORD nIn, nOut;
 CHAR buffer [BUF_SIZE];
 if (argc != 3) {
  fprintf (stderr, "Usage: cp file1 file2\n");
  return 1;
 }
 hIn = CreateFileA (argv[1], GENERIC_READ, FILE_SHARE_READ, NULL,
   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 if (hIn == INVALID_HANDLE_VALUE) {
  fprintf (stderr, "Cannot open input file. Error: %x\n", GetLastError ());
  return 2;
 }

 hOut = CreateFileA (argv[2], GENERIC_WRITE, 0, NULL,
   CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 if (hOut == INVALID_HANDLE_VALUE) {
  fprintf (stderr, "Cannot open output file. Error: %x\n", GetLastError ());
  CloseHandle(hIn);
  return 3;
 }
 while (ReadFile (hIn, buffer, BUF_SIZE, &nIn, NULL) && nIn > 0) {
  WriteFile (hOut, buffer, nIn, &nOut, NULL);
  if (nIn != nOut) {
   fprintf (stderr, "Fatal write error: %x\n", GetLastError ());
   CloseHandle(hIn); CloseHandle(hOut);
   return 4;
  }
 }
 CloseHandle (hIn);
 CloseHandle (hOut);
 return 0;
}

  1) ReadFile / WriteFile 함수는 BOOL 값을 돌려준다. 바이트 개수는 함수 인자를 통해 반환된다.

  2) GetLastError() 함수를 통해 시스템 오류 코드를 얻을 수 있다.

 


 

3. Windows API 인 CopyFile 를 이용

 

#include <windows.h>
#include <stdio.h>
#define BUF_SIZE 256

int main (int argc, char * argv [])
{
 if (argc != 3) {
  fprintf (stderr, "Usage: cp file1 file2\n");
  return 1;
 }
 if (!CopyFileA (argv[1], argv[2], FALSE)) {
  fprintf (stderr, "CopyFile Error: %x\n", GetLastError ());
  return 2;
 }
 return 0;
}

     1) CopyFile 함수는 파일 시간 같은 메타 데이터도 복사한다.

 


 

출처 : Windows 시스템 프로그래밍 윈도우즈 API 핵심 바이블

'0x001 Programming > 01. C | C++' 카테고리의 다른 글

[Example] 예외 처리  (0) 2017.12.29
[Tip] 예외 처리  (0) 2017.12.29
[Tip] 파일 잠금  (0) 2017.12.29
[Example] 디렉터리 내용 출력  (0) 2017.12.29
[Tip] 문자열 처리 관련  (0) 2017.12.29

+ Recent posts