• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#如何使用指针读取文件

OC/C/C++ 水墨上仙 2128次浏览

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)
加载中……