Danny
Danny

Reputation: 141

Problem file binary in read/write with tfilestream

Hello I need to work with very big binary files so i can't use functions such as Assign(), Closefile() etc. I want to use TFileStream for its Read()/Write() methods. But I have problem because I can't read back what I've written to the stream. I have understood that the problem was related to the encoding so I think I need to use Unicode and not Ansi. But I haven't understood how to do it. Can someone help me, with examples ? I know how to write/read from/to a file but this doesn't help me solve the problem.

Upvotes: 1

Views: 2095

Answers (3)

az01
az01

Reputation: 2018

If you want to write/read strings from/to a stream, the easy way is to cast your string as a Shortstring which is always 255 char long (but it implies that your string must not be longer than 255 chars). If you only need to read/write strings in your streams then use a TStringList instead.

Otherwise you have other more complex options:

  • write/ read a TStringList into the stream ( then you have to implement a kind of file format)
  • write the string and to retrieve it read char by char and accumulate chars until a null char is encountered, repeat the operation for each string

Upvotes: -1

Toon Krijthe
Toon Krijthe

Reputation: 53366

If you control both writing and reading, you can use readers and writers. For example:

var
  reader : TReader;
begin
  reader := TReader.Create(MyStream, BufferSize);
  try
    myString : = reader.ReadString;

  finally
    reader.Free;
  end;
end;

TReader has a way to distinguish between unicode and ansistring as long as they are written by TWriter.

If you don't controll the write part. You hopefully have a way to know the file format. (At least the strings and their size). So you can prepare a buffer to read the characters in.

Upvotes: 3

ioan ghip
ioan ghip

Reputation: 1222

Sorry, my answer was wrong, just like Andreas said. Maybe this post is going to help you? Writing a string to a TFileStream in Delphi 2010

Upvotes: 0

Related Questions