C Method of Reading Files through Pointers
- 2021-07-03 00:45:47
- OfStack
This article illustrates how C # reads a file through a pointer. Share it for your reference. The details are as follows:
// readfile.cs
// Use at compile time: /unsafe
// Parameters: readfile.txt
// Use this program to read and display text files.
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, // Filename
uint DesiredAccess, // Access mode
uint ShareMode, // Shared mode
uint SecurityAttributes, // Security attribute
uint CreationDisposition, // How to create
uint FlagsAndAttributes, // File attributes
int hTemplateFile // Handle to the template file
);
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(
IntPtr hFile, // File handle
void* pBuffer, // Data buffer
int NumberOfBytesToRead, // Number of bytes to read
int* pNumberOfBytesRead, // Number of bytes read
int Overlapped // Overlapping buffer
);
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool CloseHandle(
IntPtr hObject // Object handle
);
public bool Open(string FileName)
{
// Open an existing file for reading
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()
{
// Close the file handle
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]))
{
// Assuming you are reading ASCII Documents
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;
}
}
}
I hope this article is helpful to everyone's C # programming.