21.06.2012

Win32 Basic File Copy

Basic File Copy
  1. // BasicFileCopy.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include<Windows.h>
  6.  
  7.  
  8. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10.     HANDLE hIn, hOut;
  11.     DWORD nIn,nOut;
  12.     CHAR Buffer[BUFSIZ];
  13.  
  14.     //control the arguments
  15.     if(argc != 3)
  16.     {
  17.         printf("Usage : Basic File Copy file1 file2\n");
  18.         return 1;
  19.     }
  20.  
  21.     hIn = CreateFile(argv[1],GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
  22.     if(hIn == INVALID_HANDLE_VALUE)
  23.     {
  24.         printf("Cannot open input file. Error %x\n",GetLastError());
  25.         return 3;
  26.     }
  27.     hOut = CreateFile(argv[2],GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL);
  28.     if(hIn == INVALID_HANDLE_VALUE)
  29.     {
  30.         printf("Cannot open output file. Error %x\n",GetLastError());
  31.         return 3;
  32.     }
  33.  
  34.     while(ReadFile(hIn,Buffer,BUFSIZ,&nIn,NULL) && nIn > 0)
  35.     {
  36.         WriteFile(hOut,Buffer,nIn,&nOut,NULL);
  37.         if(nIn != nOut)
  38.         {
  39.             printf("Fatal Wrie Error: %x\n",GetLastError());
  40.             return 4;
  41.         }
  42.     }
  43.     CloseHandle(hIn);
  44.     CloseHandle(hOut);
  45.     return 0;
  46. }

1 yorum:

ugurkoltuk dedi ki...

I would close all opened handles in case of each return for the sake of consistency