Link to home
Start Free TrialLog in
Avatar of urif
urif

asked on

saving text from a file into memory

Hello all,

I have a console application that needs to read a file, get the text inside and save it into a memory stream or something the like, i need this because i will passing that text to a function and later i will show the resulting text on the screen. So this is what i need:

1. read from file.txt
2. fill a buffer with that text
3. pass the buffer to a function (this function will reverse the text)
4. show the resulting text on the screen.

any ideas how to build such a buffer?

thanx!
Avatar of kretzschmar
kretzschmar
Flag of Germany image

what about to use a tmemorystream?

it provides a loadfromfile-method,
a pointer and a size proberty

or you can even use a string
loading your text in a tsringlist and forward its text-proeprty
ASKER CERTIFIED SOLUTION
Avatar of Madshi
Madshi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hi madshi ;-)
Avatar of Madshi
Madshi

hi meikl...  (-:
Avatar of urif

ASKER

To Madshi:

Thx, are you sure the file text will fit into a normal string?

furthermore, where do you return that string?
urif, since Delphi 2, Strings can be any size up to about 2GB. So if your text file is larger, well... hm... ;-)

To reverse a string, you could use this code:

procedure SwapChar(var Data; Count: Integer);
var
     B,E: ^Byte;
     Temp: Byte;
begin
     if Count>1 then begin
          E:=@Data;
          B:=E;
          Inc(E,Count-1);
          Count:=Count shr 1;
          while Count>0 do begin
               Temp:=B^;
               B^:=E^;
               E^:=Temp;
               Inc(B);
               Dec(E);
               Dec(Count);
          end;
     end;
end;

and then after loading the text into YourString using Madshi's code:

     SwapChar(YourString[1],Length(YourString));

Easy, isn't it...
Avatar of urif

ASKER

sorry about my naivity, i'm a c programmer (in linux/unix!!!) i'm new to this windows, my pascal is the pascal learned in college

thx for your help, i really apreciated!
>> Thx, are you sure the file text will fit into a normal string?

As AvonWyss already pointed out, a string can theoretically hold up to 2 GB data. But there is a limit, namely the available RAM + swap file. Generally you can easily load text files up to 1 MB into memory, if the text files are much larger, you should think about loading it in in thunks.

>> furthermore, where do you return that string?

It works like this:

var strVar : string;
begin
  if LoadStrFromFile('c:\autoexec.bat', strVar) then begin
    // here you have the file in the "strVar"
  end else
    ShowMessage('loading failed...');

>> sorry about my naivity, i'm a c programmer

No problem...   (-:

Regards, Madshi.
Avatar of urif

ASKER

thx again