Skip to content

Instantly share code, notes, and snippets.

@JubbaSmail
Created November 13, 2014 10:58
Show Gist options
  • Select an option

  • Save JubbaSmail/94d612ca7a02902a642f to your computer and use it in GitHub Desktop.

Select an option

Save JubbaSmail/94d612ca7a02902a642f to your computer and use it in GitHub Desktop.
#include <windows.h>
#include <stdio.h>
#define BUF_SIZE 16384 /* 2^14 Optimal in several experiments. Small values such as 256 give very bad performance */
#if define UNICODE
#define CreateFile CreateFileW
#else
#define CreateFile CreateFileA
#endif
int main(int argc, LPTSTR argv[])
{
//Init File_Pointer, Counter, Buffer
HANDLE hIn, hOut;
DWORD nIn, nOut;
CHAR buffer[BUF_SIZE];
if (argc != 3) {
fprintf(stderr, "Usage: cp file1 file2\n");
return 1;
}
//Open File1
hIn = CreateFile(
argv[1], /a/LPCTSTR
GENERIC_READ, // GENERIC_READ | GENERIC_WRITE
FILE_SHARE_READ, // 0 , FILE_SHARE_READ , FILE_SHARE_WRITE
NULL, // SECURITY_ATTR
OPEN_EXISTING, //CREATE_NEW , CREATE_ALWAYS , OPEN_ALWAYS, TRUNCATE_EXISTING,
FILE_ATTRIBUTE_NORMAL, //FILE_ATTRIBUTE_READONLY , FILE_FLAG_DELETE_ON_CLOSE
NULL //TEMPLETE HANDLE
);
if (hIn == INVALID_HANDLE_VALUE) {
fprintf(stderr, "Cannot open input file. Error: %x\n", GetLastError());
return 2;
}
//Create File2
hOut = CreateFile(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;
}
//Loop
//Read to Buffer and Write to File2
while (ReadFile
(hIn, // HANDLE
buffer, //LPVIOD == CHAR[]
BUF_SIZE, // DWOED
&nIn, // LPDWORD
NULL //LPOVERLAPPED
) && 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;
}
}
//Close File1 & File2
CloseHandle(hIn);
CloseHandle(hOut);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment