• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 153
  • Last Modified:

Append a non-text file.

Is there a way to append a non-text file without copying the entire file?

I think I should use seek(filesize(f)), but with what should I open the file because I can obviously not use rewrite.
0
Stream12
Asked:
Stream12
1 Solution
 
DaFoxCommented:
Hi.

Try Reset() or even better use TFileStream:

var
  Stream1: TFileStream;
  c: char;
begin
  Stream1 := TFileStream.Create('filename', fmOpenRead);
  Stream1.Seek(1, soFromEnd);
  try
    while (Stream1.Position > 0) do
    begin
      Stream1.Read(c, SizeOf(c));
      if (Stream1.Position := 1) then break;
      Stream1.Seek(2, soFromCurrent);
    end;
  finally
    Stream1.Free;
  end;
end;

(not tested)

Markus
0
 
emadatCommented:
Try This. It works for me all the time; and even faster than TFileStream.

//**************************************************
var
     F: File;
begin
     AssignFile(F, _File_Name_);
     if FileExists(_File_Name_) then begin
          reset(F, 1);
          seek(F, FileSize(F));
     end else
          ReWrite(F, 1);
     BlockWrite(F, _Data_Buffer_, SizeOf(_Data_Buffer_));
     CloseFile(F);
end;
//**************************************************

Emad
0
 
mvieiraCommented:
This code will append a binary file with any data (I used a PChar for data, but you can use something else)


uses SysUtils;

procedure AppendDataToFile(Data:PChar);

var FHandle,TryNum,FSize:Integer;
    S:String;
    t:Integer;
    Filename:String;

begin
  Filename:='c:\test.bin';
  FHandle:=-1;
  if (NOT FileExists(Filename)) then
    FHandle:=FileCreate(Filename)  // file does not exists: create
  else
    FHandle:=FileOpen(Filename, fmOpenWrite or fmShareDenyWrite);  // file exists: open it
  if FHandle<=0 then
    raise Exception.Create('Could not open file');
  try
    FSize:=FileSeek(FHandle,0,2);
    if FileWrite(FHandle,Data^,StrLen(Data))<=0 then
      raise Exception.Create('Error writing file');
  finally
    FileClose(FHandle);
  end;
end;
0
 
LukA_YJKCommented:
Using Reset does not mean that you can only read it. You can even write to it. Try it, hope it will work.

Reset(F);
Seek(F, FileSize(F));
Write(F,d);
Close(F);
0
 
Stream12Author Commented:
It works thanks, for some reason I thought reset means readonly.

Sorry I took so long.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now