I'm doing a program in Delphi, writing in all kinds of files, either text or executable:
var
openfile: TextFile;
begin
AssignFile(openfile, 'test.exe');
Append(openfile);
WriteLn(openfile,'[test]hi world[test]');
CloseFile(openfile);
end;
How can I improve this?
-
1\$\begingroup\$ There are other ways using native file handles, but the way you have done it is the recommended one. \$\endgroup\$GiantTree– GiantTree2015年02月25日 16:57:00 +00:00Commented Feb 25, 2015 at 16:57
-
1\$\begingroup\$ Although it might not be recommenced to write text to a file with a .EXE extension ,-) \$\endgroup\$Mawg– Mawg2015年04月13日 14:15:15 +00:00Commented Apr 13, 2015 at 14:15
2 Answers 2
Yes. I would add 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;
Please note that AssignFile routines are very old fashioned. Consider using OOP approach using streams, like
var
f: TFileStream;
begin
f:=TFileStream.Create(FileName, fmCreate);
try
f.WriteBuffer(Pointer(SourceString)^, Length(SourceString));
finally
f.Free;
end;
end;
(SourceString in this case should be AnsiString. It needs a little change for Unicode)
-
\$\begingroup\$ What's wrong with using TStringStream and copying from that? \$\endgroup\$Andrea Raimondi– Andrea Raimondi2016年09月27日 14:05:14 +00:00Commented Sep 27, 2016 at 14:05
-
\$\begingroup\$ TStringStream does not work directly with the file (not suitable if you work with large files) and you can't change just specific part of it - you have to load and save whole file. \$\endgroup\$smooty86– smooty862016年09月27日 20:00:48 +00:00Commented Sep 27, 2016 at 20:00
-
\$\begingroup\$ I am not sure we are on the same page here. What I am saying is: to copy a string, why can't you use a TStringStream and then CopyFrom there. TStringStream allows you to seek and read specific strings, so it does precisely what you say it doesn't do. Or I am missing something. \$\endgroup\$Andrea Raimondi– Andrea Raimondi2016年09月28日 06:49:18 +00:00Commented Sep 28, 2016 at 6:49
-
\$\begingroup\$ This topic is "Write to files". TStringStream is a memory stream, you have to load whole file into memory, change it and save it = overwrite whole file. \$\endgroup\$smooty86– smooty862016年09月28日 07:05:54 +00:00Commented Sep 28, 2016 at 7:05