c語言程式設計檔案操作方法樣本(CreateFile和fopen)_C 語言

來源:互聯網
上載者:User

執行個體:

(1)第一種方法CreateFile

複製代碼 代碼如下:

#include "stdafx.h"
#include <windows.h>
void main(int argc, char* argv[])
{
      HANDLE hDevice = CreateFile("C://S.txt",
            GENERIC_READ|GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);
      if (hDevice == INVALID_HANDLE_VALUE)
      {
             printf("Failed to obtain file with %d error code !/n",GetLastError());
             return;
      }
      DWORD dwSize = GetFileSize(hDevice,NULL);
      printf("%d /n",dwSize);

      char chBuffer[10] = "5469";
      DWORD dwWriteSize = 0;
      BOOL bRet = WriteFile(hDevice,chBuffer,4,&dwWriteSize,NULL);
      if(bRet)
      {
             printf("write file success /n");
      }
      FlushFileBuffers(hDevice);   //將緩衝區資料寫入磁碟

      LONG IDistance = 0;
      DWORD dwPtr = SetFilePointer(hDevice,IDistance,NULL,FILE_BEGIN);  //調整檔案指標到檔案開頭
      DWORD dwReadSize = 0;
      bRet = ReadFile(hDevice,chBuffer,10,&dwReadSize,NULL);
      if (bRet)
      {
              printf("chbuffer is %s /n",chBuffer);
      }
      CloseHandle(hDevice);
      return ;
}

(2)第二種方法流檔案操作FILE

複製代碼 代碼如下:

      char datain[101];
      FILE *fp_sys;
      fp_sys = fopen("要開啟的檔案名稱", "rb"); //第二個參數為開啟方法,r代表讀,b代表二進位方式
      if(fp_sys == NULL) {
             AfxMessageBox("無法開啟儲值卡檔案");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.