Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <Windows.h>
  3. #include <iostream>
  4. #include <fstream>
  5. #include <string>
  6. using namespace std;
  7.  
  8. int copy_c(char* originalName, char* copyName)
  9. {
  10.     char buffer[BUFSIZ];
  11.  
  12.     FILE* oldFile = fopen(originalName, "rb");
  13.     if (oldFile == NULL)
  14.     {
  15.         perror(originalName);
  16.         return EXIT_FAILURE;
  17.     }
  18.  
  19.     FILE* newFile = fopen(copyName, "wb");
  20.     if (newFile == NULL)
  21.     {
  22.         perror(copyName);
  23.         return EXIT_FAILURE;
  24.     }
  25.  
  26.     size_t inBytes, outBytes;
  27.     while ((inBytes = fread(buffer, 1, BUFSIZ, oldFile)) > 0)
  28.     {
  29.         outBytes = fwrite(buffer, 1, inBytes, newFile);
  30.  
  31.         if (outBytes != inBytes)
  32.         {
  33.             perror("Failed to copy file via C functions.");
  34.             return EXIT_FAILURE;
  35.         }
  36.     }
  37.  
  38.     fclose(oldFile);
  39.     fclose(newFile);
  40.  
  41.     return EXIT_SUCCESS;
  42. }
  43.  
  44. int copy_windows(char* originalName, char* copyName)
  45. {
  46.     CHAR buffer[BUFSIZ];
  47.  
  48.     HANDLE hIn = CreateFile(originalName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
  49.     if (hIn == INVALID_HANDLE_VALUE)
  50.     {
  51.         cout << "Failed to open input file: error code " << GetLastError();
  52.         return EXIT_FAILURE;
  53.     }
  54.  
  55.     HANDLE hOut = CreateFile(copyName, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);
  56.     if (hOut == INVALID_HANDLE_VALUE)
  57.     {
  58.         cout << "Failed to open output file: error code " << GetLastError();
  59.         return EXIT_FAILURE;
  60.     }
  61.  
  62.     DWORD nIn, nOut;
  63.     while (ReadFile(hIn, buffer, BUFSIZ, &nIn, NULL) && nIn > 0)
  64.     {
  65.         WriteFile(hOut, buffer, nIn, &nOut, NULL);
  66.         if (nIn != nOut)
  67.         {
  68.             cout << "Failed to copy file: error code " << GetLastError();
  69.             return EXIT_FAILURE;
  70.         }
  71.     }
  72.  
  73.     CloseHandle(hIn);
  74.     CloseHandle(hOut);
  75.  
  76.     return EXIT_SUCCESS;
  77. }
  78.  
  79. int copy_copyfile(char* originalName, char* copyName)
  80. {
  81.     int success = CopyFile(originalName, copyName, FALSE);
  82.     if (!success) cout << "Failed to copy file: error code " << GetLastError();
  83.     return success ? EXIT_SUCCESS : EXIT_FAILURE;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement