简体   繁体   中英

TFileStream.Read not reading last part of file

I'm using TFileStream.Read in a loop to read a text file, but I find that the last part is not being read into the buffer - although the total number of bytes being read is equal to the filesize.

This is my code:

procedure TForm1.DoImport;
var
  f: String;
  fs: TFileStream;
  r, c: Integer;
  buf: TBytes;

const
  bufsiz = 16384;
begin
  SetLength(buf, bufsiz);

  f := 'C:\Report\Claims\Claims.csv';

  fs := TFileStream.Create(f, fmOpenRead);
  try
    c := 0;
    repeat

      r := fs.Read(buf, bufsiz);

      Inc(c, r);

    until (r <> bufsiz);

    showmessage('Done. ' + IntToStr(c)); // <-- c equals to filesize !!

    Memo1.Text := StringOf(buf); // <-- but the memo does not show the last chunk of the file

  finally
    fs.Free;
  end;

end;

At the end, the TMemo does not contain the last chunk of the file, but the 2nd to last chunk. Is there something wrong with my code?

Thanks in advance!

The beginning of that buffer contains the last chunk of your file. But after that comes the content of the previous chunk, because you never cleared the buffer. So you think that your memo contains the previous chunk, but it is a mix of both.

You could use the copy function in order to just add a part of the buffer.

Memo1.Text := StringOf(Copy(buf, 0, r)); // r is the number of bytes to copy

A better way for reading a text file is using TStringList or TStringReader . These will take care of the file encoding (Ansi, UTF8, ...) I usually prefer the TStringList because I had too much trouble with some of the bugs in TStringReader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM