Gallery
Software
Music
Programming
Archive
Saturday, Feb 23 Week 8

FileToMem & MemToFile

Read a file into a memory buffer and write a memory buffer to a file.

Open a handle to read a file

function fileOpenRead(pFileName:pAnsiChar):THandle;
const
ac = GENERIC_READ;
sh = FILE_SHARE_READ;
attr = FILE_ATTRIBUTE_READONLY;
begin
result:=windows.createFileA(pFileName,ac,sh,nil,OPEN_EXISTING,attr,0);
end;

Open a handle to write a file

function fileOpenWrite(pFileName:pAnsiChar):THandle;
const
ac = GENERIC_READ or GENERIC_WRITE;
sh = FILE_SHARE_READ;
attr = FILE_ATTRIBUTE_NORMAL;
begin
result:=windows.createFileA(pFileName,ac,sh,nil,CREATE_ALWAYS,attr,0);
end;

Read a file into a memory buffer

function fileToMemA(pFileName:pAnsiChar;var p:pointer;var uBufSz:longWord;bAddNull:boolean):boolean;
var h:THandle;n:longWord;
begin
result:=false;p:=nil;if pFileName=nil then exit;
uBufSz:=getFileSizeA(pFileName);if uBufSz=0 then exit;
h:=fileOpenRead(pFileName);if h=INVALID_HANDLE_VALUE then exit;
try
getMem(p,uBufSz+byte(bAddNull));
if windows.readFile(h,p^,uBufSz,n,nil) and (n=uBufSz) then result:=true;
if result and bAddNull then (pAnsiChar(p)+uBufSz)^:=#0;
except result:=false end;
if not result then begin p:=nil;uBufSz:=0 end;
windows.closeHandle(h);
end;

Write a file from a memory buffer

function memToFileA(pFileName:pAnsiChar;pBuf:pointer;uBufSz:longWord):boolean;
var h:THandle;n:longWord;
begin
result:=false;if (pFileName=nil) or (pBuf=nil) or (uBufSz=0) then exit;
h:=fileOpenWrite(pFileName);
if h<>INVALID_HANDLE_VALUE then try
if windows.writeFile(h,pBuf^,uBufSz,n,nil) and (n=uBufSz) then result:=true;
except result:=false end;
windows.closeHandle(h);
end;

Examples

Related pages of FileToMem & MemToFile

Programming
Delphi programming
File formats and fileinfo
Read file header into memory