Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 '15 at 16:57
1  
Although it might not be recommenced to write text to a file with a .EXE extension ,-) – Mawg Apr 13 '15 at 14:15
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
    
What's wrong with using TStringStream and copying from that? – Andrea Raimondi Sep 27 '16 at 14:05
    
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. – smooty86 Sep 27 '16 at 20:00
    
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. – Andrea Raimondi Sep 28 '16 at 6:49
    
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. – smooty86 Sep 28 '16 at 7:05

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.