Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
1  
There are other ways using native file handles, but the way you have done it is the recommended one. –  GiantTree Feb 25 at 16:57
1  
Although it might not be recommenced to write text to a file with a .EXE extension ,-) –  Mawg Apr 13 at 14:15

2 Answers 2

up vote 6 down vote accepted

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;
share|improve this answer

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)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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