Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <Windows.h>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     HANDLE hFile;
  9.     BOOL bFile;
  10.     char chBuffer[] = "abc";
  11.     DWORD dwNumBytesToWrite = strlen(chBuffer) + 1;
  12.     DWORD wNumBytesWritten = 0;
  13.     char* chBufferRead = new char[strlen(chBuffer) + 1];
  14.     DWORD dwNumBytesToRead = strlen(chBuffer) + 1;
  15.     DWORD wNumBytesRead = 0;
  16.  
  17.     hFile = CreateFile(
  18.                 L"WriteFile.txt",
  19.                 GENERIC_READ | GENERIC_WRITE,
  20.                 FILE_SHARE_READ | FILE_SHARE_WRITE,
  21.                 NULL,
  22.                 CREATE_ALWAYS,
  23.                 FILE_ATTRIBUTE_NORMAL,
  24.                 NULL);
  25.     if (hFile == INVALID_HANDLE_VALUE)
  26.     {
  27.         cout << "CreateFile failed with Error number: " << GetLastError() << endl;
  28.     }
  29.     else
  30.     {
  31.         cout << "CreateFile Success " << endl;
  32.     }
  33.  
  34.     //Write to file
  35.     bFile = WriteFile(
  36.                 hFile,
  37.                 chBuffer,
  38.                 dwNumBytesToWrite,
  39.                 &wNumBytesWritten,
  40.                 NULL);
  41.  
  42.     if (bFile == FALSE)
  43.     {
  44.         cout << "WriteFile failed with Error" << GetLastError() << endl;
  45.     }
  46.     else
  47.     {
  48.         cout << "WriteFile Success " << endl;
  49.     }
  50.  
  51.     //Read from file
  52.     bFile = ReadFile(
  53.         hFile,
  54.         chBufferRead,
  55.         dwNumBytesToRead,
  56.         &wNumBytesRead,
  57.         NULL);
  58.  
  59.     if (bFile == FALSE)
  60.     {
  61.         cout << "ReadFile failed with Error" << GetLastError() << endl;
  62.     }
  63.     else
  64.     {
  65.         cout << "ReadFile Success " << endl;
  66.         cout << "Data read from file: " << chBufferRead << endl;
  67.     }
  68.  
  69.     delete chBufferRead;
  70.  
  71.     if (CloseHandle(hFile))
  72.     {
  73.         cout << "Handle closed" << endl;
  74.     }
  75.  
  76.     system("PAUSE");
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement