C#通过指针读取文件的方法
本文实例讲述了C#通过指针读取文件的方法。分享给大家供大家参考。具体如下:
//readfile.cs
//编译时使用:/unsafe
//参数:readfile.txt
//使用该程序读并显示文本文件。
usingSystem;
usingSystem.Runtime.InteropServices;
usingSystem.Text;
classFileReader
{
constuintGENERIC_READ=0x80000000;
constuintOPEN_EXISTING=3;
IntPtrhandle;
[DllImport("kernel32",SetLastError=true)]
staticexternunsafeIntPtrCreateFile(
stringFileName,//文件名
uintDesiredAccess,//访问模式
uintShareMode,//共享模式
uintSecurityAttributes,//安全属性
uintCreationDisposition,//如何创建
uintFlagsAndAttributes,//文件属性
inthTemplateFile//模板文件的句柄
);
[DllImport("kernel32",SetLastError=true)]
staticexternunsafeboolReadFile(
IntPtrhFile,//文件句柄
void*pBuffer,//数据缓冲区
intNumberOfBytesToRead,//要读取的字节数
int*pNumberOfBytesRead,//已读取的字节数
intOverlapped//重叠缓冲区
);
[DllImport("kernel32",SetLastError=true)]
staticexternunsafeboolCloseHandle(
IntPtrhObject//对象句柄
);
publicboolOpen(stringFileName)
{
//打开现有文件进行读取
handle=CreateFile(
FileName,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0);
if(handle!=IntPtr.Zero)
returntrue;
else
returnfalse;
}
publicunsafeintRead(byte[]buffer,intindex,intcount)
{
intn=0;
fixed(byte*p=buffer)
{
if(!ReadFile(handle,p+index,count,&n,0))
return0;
}
returnn;
}
publicboolClose()
{
//关闭文件句柄
returnCloseHandle(handle);
}
}
classTest
{
publicstaticintMain(string[]args)
{
if(args.Length!=1)
{
Console.WriteLine("Usage:ReadFile<FileName>");
return1;
}
if(!System.IO.File.Exists(args[0]))
{
Console.WriteLine("File"+args[0]+"notfound.");
return1;
}
byte[]buffer=newbyte[128];
FileReaderfr=newFileReader();
if(fr.Open(args[0]))
{
//假定正在读取ASCII文件
ASCIIEncodingEncoding=newASCIIEncoding();
intbytesRead;
do
{
bytesRead=fr.Read(buffer,0,buffer.Length);
stringcontent=Encoding.GetString(buffer,0,bytesRead);
Console.Write("{0}",content);
}
while(bytesRead>0);
fr.Close();
return0;
}
else
{
Console.WriteLine("Failedtoopenrequestedfile");
return1;
}
}
}
希望本文所述对大家的C#程序设计有所帮助。