delphifile-iotext-filespascal

Reading from a file in Pascal


I read a file of integers, each on a new line, like this:

function arrayFromFile(nameFile : string) : pole;
var
    userFile : text;
    d : data;
    i : integer;
    p : array;
begin
    assign(userFile, nameFile);
    reset(userFile);
    i:=0;
    repeat
        inc(i);
        readln(userFile, d);
        p[i]:=d;
    until eof(userFile);
    close(userFile);
    arrayFromFile:=p;
end;

And I iterate through the array like this:

procedure writeArray(p : array);
var
    i : integer;
begin
    i:=0;
    while p[i+1]<>0 do begin
        inc(i);
        writeln(p[i]);
    end;
end;

Then, when I do

A:=arrayFromFile('file1');
B:=arrayFromFile('file2');
writeArray(A);
writeln;
writeArray(B);

if A is longer (there are more lines), it writes out A fine, but B has suddenly the same length and the remaining lines are filled with integers from A!

Do you have any idea why and how to avoid this behaviour?


Solution

  • Without a complete picture of usage this is hard to say, but your read routine doesn't seem to keep track of the number of elements read, since it doesn't conserve the final value of I

    In the write routine you seem to assume that an element with value 0 is the end of the array. If this is the general "end of array" convention, maybe a

    inc(i);
    p[i]:=0;
    

    after the until in the read routine will solve your problem (assuming your arrays are declared large enough to hold the largest file +1 element.