5
\$\begingroup\$

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?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ There are other ways using native file handles, but the way you have done it is the recommended one. \$\endgroup\$
    – GiantTree
    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\$ Apr 13, 2015 at 14:15

2 Answers 2

8
\$\begingroup\$

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;
\$\endgroup\$
0
3
\$\begingroup\$

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)

\$\endgroup\$
4
  • \$\begingroup\$ What's wrong with using TStringStream and copying from that? \$\endgroup\$ 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
    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\$ 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
    Sep 28, 2016 at 7:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.