Reading data from a text file into an array

FlamingClaw FlamingClaw is offline Offline Apr 26th, 2009, 3:32 pm |
0
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.
Quick reply to this message  
Pascal and Delphi Syntax
  1. Program Solution01;
  2.  
  3. Var i:Byte;
  4. data:array[1..10]of String;{your array}
  5. F:Text;{file's variable}
  6. FileName:String;{stores the file's name and path}
  7. Lines:String;
  8. Counter:Integer;
  9.  
  10. Procedure FileReadInToArray;
  11. Begin
  12. FileName:='C:\yourfile.txt';
  13. Assign(F,FileName);
  14. {$I-}
  15. Reset(F); {open for reading}
  16. {$I+}
  17. If (IoResult = 0) Then Begin
  18. Counter:=1;
  19. While Not(EoF(F)) Do Begin
  20. ReadLn(F,Lines);
  21. Data[Counter]:=Lines;
  22. If (EoF(F)) Then Break;
  23. Inc(Counter);{increase 'Counter' by 1}
  24. End; {of while}
  25. End
  26. Else WriteLn('Error when reading the file');
  27. Close(F);
  28. End;
  29.  
  30. Begin {main}
  31. FileReadInToArray; {calling our procedure}
  32. For i:=1 To 10 Do WriteLn(i,'. element: ',Data[i]);
  33. ReadLn;
  34. End.{end of main}
  35.  
  36. {
  37.  
  38. the contents of yourfile.txt
  39. One word one line
  40.  
  41. apple
  42. window
  43. pascal
  44. wine
  45. next
  46. day
  47. sun
  48. rain
  49. peach
  50. computer
  51.  
  52. -=Created by FlamingClaw=-
  53. Written and tested in Dev Pascal 1.9.2. By me
  54. -=2009.04.26=-
  55. }

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC