Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Put buffer from TFileStream.Read() into string

Status
Not open for further replies.

aik2

Programmer
Jun 10, 2003
21
Hello All !

Please help, how to
put buffer from TFileStream.Read() into string?
 
1) Declare a variable of type String.
2) Pass this variable into the TFileStream.Read method as the second parameter (i.e. you pass in your string variable as the buffer argument).

As far as I know, you can pass any variable in as the buffer argument because it is an untyped variable. However, this can produce unpredictable results as not all variables will be compatible.

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
I don't think that Clive's solution will work because the string needs to be large enough to contain the data you want to read.

You can to do something like the following. In this example, I have specified a maximum buffer size of 1K bytes.

Code:
procedure TForm1.ReadStreamClick(Sender: TObject);
const
  Max = 1024;
var
  stream: TFileStream;
  buffer: pchar;
begin
  stream := TFileStream.Create ( FileName, fmOpenRead );
  try
    GetMem ( buffer, Max );
    try
      stream.read ( buffer^, Max );
      Edit1.Text := StrPas ( buffer );
    finally
      FreeMem ( buffer );
    end;
  finally
    stream.free;
  end;
end;

Andrew
 
Yes, but file contains #0 so buffer as PChar returns only the part of file, as for buffer as string - there are fatal error when try to access string.


 
If you want to use a string as the buffer you MUST set its length to the maximum length required before you read in the data from the stream. For example:
Code:
procedure TForm1.ReadStreamClick(Sender: TObject);
const
  MaxLen = 1024;
var
  buffer: string;
  stream: TFileStream;
begin
  SetLength ( buffer, MaxLen );
  stream := TFileStream.Create ( YourFileName, MaxLen );
  try
    stream.read ( pchar(buffer)^, MaxLen );
    Edit1.Text := buffer;
  finally
    stream.free;
  end;
end;

#0 is used to signify the end of a string. How do you want to handle the #0 character? They could be converted to space characters, for example.

Perhaps you want the file converted into a String List?

Andrew

 
Ok, must be here is the solution: I just have to read stream cyclicaly and put this into stringlist until receive all bytes from the file
 
Or just make the string big enough to hold the whole file:
Code:
with TFileStream.Create(AFileName, fmOpenRead) do
try
   SetLength(AString, Size);
   Read(PChar(AString)^, Size);
finally
   Free;
end;

You might want a reasonableness test on the .Size of the file, but this will work.

Cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top