使用WindowsAPI進行WriteFile 和 ReadFile

應用程式  ---> Windows API –—> Windows 作業系統


   1: #include "stdafx.h"
   2: #include <Windows.h>
   3: #include <iostream>
   4:  
   5: using namespace std;
   6:  
   7: int _tmain(int argc, _TCHAR* argv[])
   8: {
   9:     // 寫入檔案
  10:     HANDLE hFile;
  11:     DWORD nBytes;
  12:     hFile = CreateFile( _T("test.txt"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
  13:     char msg[] = "我要寫入1";
  14:     if( hFile != INVALID_HANDLE_VALUE)
  15:     {
  16:         WriteFile(hFile, msg, sizeof(msg)-1, &nBytes, NULL);
  17:         CloseHandle(hFile);
  18:         cout << "寫入內容: " << msg << endl; 
  19:             
  20:         cout << "寫入 "    << nBytes << " Bytes" << endl;
  21:         system("pause");
  22:     }
  23:     //-------------------------------------------------
  24:     // 讀取檔案
  25:     hFile = CreateFile( _T("test.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL);
  26:     if(hFile != INVALID_HANDLE_VALUE )
  27:     {
  28:         char line[256] = {0};
  29:         BOOL bResult;
  30:         bResult = ReadFile(hFile, line, sizeof(line), &nBytes, NULL);
  31:         if(nBytes!=0)
  32:         {
  33:             cout << "讀入內容: " << endl;
  34:             cout << line << endl;
  35:         }
  36:         CloseHandle(hFile);
  37:         system("pause");
  38:     }
  39:     return 0;
  40: }
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()