当前位置: 移动技术网 > IT编程>开发语言>c# > C#通过指针读取文件的方法

C#通过指针读取文件的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例讲述了c#通过指针读取文件的方法。分享给大家供大家参考。具体如下: // readfile.cs // 编译时使用:/unsafe // 参数:rea

本文实例讲述了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#程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网