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

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

(0)

相关推荐

  • C# Pointer指针应用实例简述

    本文所述为在C#中使用Pointer指针的简单示例,非常适合新手参考学习.该实例演示了字符串的加密及解密的过程,将字符串指针p指向字符数组b,并将参数p传给函数,以及对给定字符串进行加密处理. 具体实例代码如下: using System; namespace PointerDemo { public class PointerDemo { public static void Main() { string s = "Hello Csharp!"; // 原字符串 Console.W

  • C#中this指针的用法示例

    本文实例展示了C#中this指针的用法,对于初学者进一步牢固掌握C#有很大帮助,具体内容如下: 一.this指针是什么: 这里有一些面向对象编程的概念需要说明:类(Class)的概念和对象(Object)的概念 类是对事物概括,也是C#编码时所有代码归属的基本单位:而对象是对类的实例化,也就是C#里new方法的返回值.写代码是不能直接用操作类,而只能先实例化类,然后我们用这个类被实例化后的对象. 通俗一些的说明是,"类"好比是"人"的概念,而我们把类实例化后,就成为

  • 浅谈C#指针问题

    花了很长时间的实践,终于搞清楚了.类或者链表等,在指针赋值的时候,会使用新的指针.比如: Foo a = c; Foo b = new Foo(); Foo a = b; 这种情况下,会把b的指针传给a,a不再指向c,a以后的操作都会对b生效. 如下情况下: Foo b = new Foo(); Foo a{get {return b;}} 这种情况下,表示a无法被修改,但是如果你a.bar = 5;的话,那么是可以修改的,为什么呢?因为此时任何针对a的属性的修改,本质上都是对b的修改,只有a

  • c# List find()方法返回值的问题说明(返回结果为对象的指针)

    C#中List<T>中泛型T如果是一个对象的话,则利用Find函数返回的将是这个对象的指针,对其返回对象的属性进行操作,也会影响list中相应元素对象的值.验证如下:1.新建一个Class1类,其含有两个姓名和分数两个属性: 复制代码 代码如下: <SPAN style="FONT-SIZE: 18px">    public class Class1    {        public string name{ get; set; }        publ

  • C#通过指针实现快速拷贝的方法

    本文实例讲述了C#通过指针实现快速拷贝的方法.分享给大家供大家参考.具体实现方法如下: // fastcopy.cs // 编译时使用:/unsafe using System; class Test { // unsafe 关键字允许在下列 // 方法中使用指针: static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count) { if (src == null || srcIndex

  • C#委托所蕴含的函数指针概念详细解析

    原则: 1.函数指针,实际上是函数编码后的指令在内存中的首地址,在C++/C中,这个地址可以用函数名直接使用 一个函数调用另一个函数的时候,就可以把被调用函数以函数指针的形式作为参数传入 2.回调函数callback使用的技术就是函数指针: 回调函数就好像是一个中断处理函数,系统在符合你设定的条件时自动调用.为此,你需要做三件事: 1). 声明: 2). 定义: 3). 设置触发条件,就是在你的函数中把你的回调函数名称转化为地址作为一个参数,以便于DLL调用. 回调函数是应用程序提供给Windo

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

    本文实例讲述了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

  • python使用fileinput模块实现逐行读取文件的方法

    本文实例讲述了python使用fileinput模块实现逐行读取文件的方法.分享给大家供大家参考.具体实现方法如下: #-------------------------------- # Name: read_lines.py # Author: Kevin Harris # Last Modified: 02/13/04 # Description: This Python script demonstrates # how to use fileinput to read # each l

  • C#中winform使用相对路径读取文件的方法

    本文实例讲述了C#中winform使用相对路径读取文件的方法.分享给大家供大家参考.具体分析如下: 目录结构如下图所示:   方法一:由于生成的exe文件在bin\debug目录下,可以使用向上查找目录的方式获取要读取的xml文件 复制代码 代码如下: string haarXmlPath = @"../../haarcascade_frontalface_alt_tree.xml"; FileInfo file = new FileInfo(fileName); string  fu

  • php从文件夹随机读取文件的方法

    本文实例讲述了php从文件夹随机读取文件的方法.分享给大家供大家参考.具体实现方法如下: function RandomFile($folder='', $extensions='.*'){ // fix path: $folder = trim($folder); $folder = ($folder == '') ? './' : $folder; // check folder: if (!is_dir($folder)){ die('invalid folder given!'); }

  • C#使用文件流读取文件的方法

    本文实例讲述了C#使用文件流读取文件的方法.分享给大家供大家参考.具体如下: using System; using System.IO; namespace Client.Chapter_11___File_and_Streams { public class OpenExistingFile { static void Main(string[] args) { FileInfo MyFile = new FileInfo(@"c:\Projects\Testing.txt");

  • C#逐行读取文件的方法

    本文实例讲述了C#逐行读取文件的方法.分享给大家供大家参考.具体如下: 这里使用C#逐行读取文件,对于大文件的读取非常有用. StreamReader sr = new StreamReader("fileName.txt"); string line; while((line= sr.ReadLine()) != null) { Console.WriteLine("xml template:"+line); } if (sr != null)sr.Close()

  • Java基于IO流读取文件的方法

    本文实例讲述了Java基于IO流读取文件的方法.分享给大家供大家参考,具体如下: public static void readFile(){ String pathString = TEST.class.getResource("/simu").getFile(); try { pathString = URLDecoder.decode(pathString, "utf-8"); } catch (UnsupportedEncodingException e1)

  • C#使用StreamReader读取文件的方法

    本文实例讲述了C#使用StreamReader读取文件的方法.分享给大家供大家参考.具体实现方法如下: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace W { class Program { static void Main(string[] args) { u

  • Python 多线程不加锁分块读取文件的方法

    多线程读取或写入,一般会涉及到同步的问题,否则产生的结果是无法预期的.那么在读取一个文件的时候,我们可以通过加锁,但读不像写操作,会导致文件错误,另外锁操作是有一定的耗时.因此通过文件分块,可以比较有效的解决多线程读问题,之前看到有人写的分块操作,比较复杂,需要实现建立好线程以及所读取块信息,在这里,我提供了一种比较简便的方法,以供参考. #!/user/bin/env python #_*_coding:utf-8_*_ from threading import Thread import

  • C# StreamReader类实现读取文件的方法

    在 C# 语言中 StreamReader 类用于从流中读取字符串.它继承自 TextReader 类. StreamReader 类的构造方法有很多,这里介绍一些常用的构造方法,如下表所示. 构造方法 说明 StreamReader(Stream stream) 为指定的流创建 StreamReader 类的实例 StreamReader(string path) 为指定路径的文件创建 StreamReader 类的实例 StreamReader(Stream stream, Encoding

随机推荐