Author: Jonas Bilinkevicius
What is the easiest way to import a comma delimited text file and assign the
different elements of a line of data in that file to variables?
Answer:
1 function GetNextField(var Line: string; Sep: Char = '|'): string;
2 {Extracts the first field from Line, delimited by Sep, using the
3 pipe character as the default delimeter}
4 var
5 SepPos: Integer;
6 begin
7 {Finds the position of the first occurrence of Sep in Line}
8 SepPos := Pos(Sep, Line);
9 {If found...}
10 if SepPos > 0 then
11 begin
12 {There are fields; copy the first to Result}
13 Result := Copy(Line, 1, SepPos - 1);
14 {Delete first field from Line, including the delimeter}
15 Delete(Line, 1, SepPos);
16 end
17 else
18 begin
19 {No more fields; copy entire Line to Result}
20 Result := Line;
21 {Return a null Line}
22 Line := '';
23 end;
24 end;
25
26 //This function can be used with TextFiles, FileStreams, MemoryStreams,
27 StringLists, arrays of strings, etc. I will give you a very basic example of how I
28 write and then read back text files. Here is a writer:
29
30 procedure WriteToFile;
31 var
32 Line: string;
33 TempFile: TextFile;
34 begin
35 {Initialize the file}
36 AssignFile(TempFile, 'Some\Path\Here');
37 {Open the file for output}
38 Rewrite(TempFile);
39 try
40 {Scan source table until EOF}
41 MyTable.First;
42 while not MyTable.EOF do
43 begin
44 {Build the line}
45 Line := MyTableAINTEGERFIELD.AsString + '|';
46 Line := Line + MyTableAFLOATFIELD.AsString + '|';
47 Line := Line + MyTableASTRINGFIELD.AsString + '|';
48 {Write the line}
49 Writeln(TempFile, Line);
50 {Move to next record}
51 MyTable.Next;
52 end;
53 finally
54 {Close the file}
55 CloseFile(TempFile);
56 end;
57 end;
58
59 //And here is a reader:
60
61 procedure ReadFromFile;
62 var
63 AInteger: Integer;
64 AFloat: Extended;
65 AString, Line: string;
66 TempFile: TextFile;
67 begin
68 {Initialize the file}
69 AssignFile(TempFile, 'Some\Path\Here');
70 {Open the file for input}
71 Reset(TempFile);
72 try
73 {Read lines until EOF}
74 while not Eof(TempFile) do
75 begin
76 {Read a line}
77 Readln(TempFile, Line);
78 {Assign fields to variables}
79 AInteger := StrToInt(GetNextField(Line));
80 AFloat := StrToFloat(GetNextField(Line));
81 AString := GetNextField(Line);
82 end;
83 finally
84 {Close the file}
85 CloseFile(ArqTexto);
86 end;
87 end;
These are only basic examples. You must fine tune the error handling to your needs. And, of course, the examples assume your table is allready open and you know in advance how many fields there are in a line.
|