[comp.lang.pascal] Block reading a text file

filbo@gorn.santa-cruz.ca.us (Bela Lubkin) (09/12/89)

In article <8Z2az8G00WB8M1AUcT@andrew.cmu.edu> Douglas Allen Luce writes:
>I'm trying to read the contents of a text file into memory and have a single
>pointer to it.  I quickly figured up a couple of different ways to do this:
[count the characters in the file, allocate memory, and read them; or read
line by line.]

You want the text in a single contiguous chunk of memory?  The easiest way
to do that is:

Var
  TextFile: File;  {n.b. NOT Text}
  TextLength: Word;
  TextPointer: ^Char;
..
  Reset(TextFile,1);
  TextLength:=FileSize(TextFile);
  GetMem(TextPointer,TextLength);
  BlockRead(TextFile,TextPointer^,TextLength);
  Close(TextFile);

Needs some error handling, of course.  Biggest problem: can't handle text
files > 64K.  But then it's a bit of a stretch to claim that memory is
"contiguous" if you have to reload segment registers to span it, anyway.

>  while not eof(textfile) do begin
>    readln(textfile,st);
>    getmem(pst,length(st)+1); {add one for string[0] byte}
>    pst^:=st;
>    if totalpointer=nil then totalpointer:=pst;
>  end;
> 
>I would figure this works IF getmem returns contiguous blocks of
>memory each time it is called in sequence; is this true?  And are
>there other operations (other than new) that would interfere with getmem
>returning contiguous blocks?
Well, >if< this is the only thing you ever do with the heap, and you only
do it once, etc., you will probably get contiguous blocks.  However, the
text still won't be the same as in the file: instead of CR/LF separators
between lines, it will have string length-bytes.

Bela Lubkin     * *   filbo@gorn.santa-cruz.ca.us   CIS: 73047,1112
     @        * *     ...ucbvax!ucscc!gorn!filbo    ^^^  REALLY slow [months]
R Pentomino     *     Filbo @ Pyrzqxgl (408) 476-4633 & XBBS (408) 476-4945