国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#通過指針讀取文件的方法

2020-01-24 01:40:33
字體:
來源:轉載
供稿:網友

本文實例講述了C#通過指針讀取文件的方法。分享給大家供大家參考。具體如下:

// readfile.cs// 編譯時使用:/unsafe// 參數:readfile.txt// 使用該程序讀并顯示文本文件。using System;using System.Runtime.InteropServices;using System.Text;class FileReader{  const uint GENERIC_READ = 0x80000000;  const uint OPEN_EXISTING = 3;  IntPtr handle;  [DllImport("kernel32", SetLastError=true)]  static extern unsafe IntPtr CreateFile(    string FileName,        // 文件名    uint DesiredAccess,        // 訪問模式    uint ShareMode,          // 共享模式    uint SecurityAttributes,    // 安全屬性    uint CreationDisposition,    // 如何創建    uint FlagsAndAttributes,    // 文件屬性    int hTemplateFile        // 模板文件的句柄    );  [DllImport("kernel32", SetLastError=true)]  static extern unsafe bool ReadFile(    IntPtr hFile,          // 文件句柄    void* pBuffer,        // 數據緩沖區    int NumberOfBytesToRead,  // 要讀取的字節數    int* pNumberOfBytesRead,    // 已讀取的字節數    int Overlapped        // 重疊緩沖區    );  [DllImport("kernel32", SetLastError=true)]  static extern unsafe bool CloseHandle(    IntPtr hObject // 對象句柄    );  public bool Open(string FileName)  {    // 打開現有文件進行讀取    handle = CreateFile(      FileName,      GENERIC_READ,      0,       0,       OPEN_EXISTING,      0,      0);    if (handle != IntPtr.Zero)      return true;    else      return false;  }  public unsafe int Read(byte[] buffer, int index, int count)   {    int n = 0;    fixed (byte* p = buffer)     {      if (!ReadFile(handle, p + index, count, &n, 0))        return 0;    }    return n;  }  public bool Close()  {    // 關閉文件句柄    return CloseHandle(handle);  }}class Test{  public static int Main(string[] args)  {    if (args.Length != 1)    {      Console.WriteLine("Usage : ReadFile <FileName>");      return 1;    }    if (! System.IO.File.Exists(args[0]))    {      Console.WriteLine("File " + args[0] + " not found.");       return 1;    }    byte[] buffer = new byte[128];    FileReader fr = new FileReader();    if (fr.Open(args[0]))    {      // 假定正在讀取 ASCII 文件      ASCIIEncoding Encoding = new ASCIIEncoding();      int bytesRead;      do       {        bytesRead = fr.Read(buffer, 0, buffer.Length);        string content = Encoding.GetString(buffer,0,bytesRead);        Console.Write("{0}", content);      }      while ( bytesRead > 0);      fr.Close();      return 0;    }    else    {      Console.WriteLine("Failed to open requested file");      return 1;    }  }}

希望本文所述對大家的C#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 玉门市| 余姚市| 东乡族自治县| 太保市| 郸城县| 珠海市| 静乐县| 星子县| 连城县| 慈溪市| 富川| 年辖:市辖区| 南木林县| 天柱县| 安溪县| 泰兴市| 阳高县| 同仁县| 潍坊市| 慈溪市| 镇康县| 古田县| 揭西县| 迁安市| 阳信县| 康乐县| 凤阳县| 西青区| 日喀则市| 景德镇市| 青铜峡市| 南投市| 枝江市| 星子县| 新巴尔虎右旗| 林州市| 商城县| 腾冲县| 呼图壁县| 莲花县| 鹤山市|