snippetMinor
Write to files in Delphi
Viewed 0 times
delphifileswrite
Problem
I'm doing a program in Delphi, writing in all kinds of files, either text or executable:
How can I improve this?
var
openfile: TextFile;
begin
AssignFile(openfile, 'test.exe');
Append(openfile);
WriteLn(openfile,'[test]hi world[test]');
CloseFile(openfile);
end;How can I improve this?
Solution
Yes. I would add
also, you say you want to write binary files as well as text files.. so don't use
try..finally so that the file will be properly closed even in the case of exception (hopefully my remembrance of the syntax isn't too rusty):var
openfile: TextFile;
begin
AssignFile(openfile, 'test.exe');
Append(openfile);
try
WriteLn(openfile,'[test]hi world[test]');
finally
CloseFile(openfile);
end;
end;also, you say you want to write binary files as well as text files.. so don't use
TextFile. The "modern" way would be to use TFileStream:with TFileStream.Create('test.exe', fmOpenWrite) do
try
Seek(0,soFromEnd);
Write(...);
finally
Free;
end;Code Snippets
var
openfile: TextFile;
begin
AssignFile(openfile, 'test.exe');
Append(openfile);
try
WriteLn(openfile,'[test]hi world[test]');
finally
CloseFile(openfile);
end;
end;with TFileStream.Create('test.exe', fmOpenWrite) do
try
Seek(0,soFromEnd);
Write(...);
finally
Free;
end;Context
StackExchange Code Review Q#82583, answer score: 8
Revisions (0)
No revisions yet.