Reading data from a text file into an array

FlamingClaw 1 Tallied Votes 3K Views Share

Our text file contains 10 words,and located in C:\ drive,we will read this data into an array and write out the results to the screen
Created by FlamingClaw 2009.04.26.

Program Solution01;

Var i:Byte;
    data:array[1..10]of String;{your array}
    F:Text;{file's variable}
    FileName:String;{stores the file's name and path}
    Lines:String;
    Counter:Integer;

Procedure FileReadInToArray;
Begin
FileName:='C:\yourfile.txt';
Assign(F,FileName);
{$I-}
Reset(F); {open for reading}
{$I+}
If (IoResult = 0) Then Begin
   Counter:=1;
   While Not(EoF(F)) Do Begin
      ReadLn(F,Lines);
      Data[Counter]:=Lines;
      If (EoF(F)) Then Break;
      Inc(Counter);{increase 'Counter' by 1}
   End; {of while}
End
Else WriteLn('Error when reading the file');
Close(F);
End;

Begin {main}
    FileReadInToArray;  {calling our procedure}
    For i:=1 To 10 Do WriteLn(i,'. element: ',Data[i]);
   ReadLn;
End.{end of main}

{

the contents of yourfile.txt
One word one line

apple
window
pascal
wine
next
day
sun
rain
peach
computer

-=Created by FlamingClaw=-
Written and tested in Dev Pascal 1.9.2. By me
-=2009.04.26=-
}
gurisa 0 Newbie Poster

Thank you very much, this is very useful for me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.