where : ibrtses delphi
CSV - comma separated files
disclaimer
the source code of this page may not appear correctly in certain browsers
due to special characters. Have a look at the source of this HTML page
with notepad instead
Comma separated files are useful to store data tables with integer & float
in readable textfiles. It is line oriented and one one data set is a line.
A table such as :
item1 1 001232 1.2345
item2 2 234561 2.453
item3 3 123456 3.1245
is stored as :
item1,1,001232,1.2345
item2,2,234561,2.453
item3,3,123456,3.1245
processing
reading and writing them is simple :
writing to a CSV
Write a line with the usual formatting.
assignfile(f,'xxxxx.csv');
rewrite(f);
for j:=0 to lines-1 do begin
writeln(f,.....);
closefile(f);
Reading a CSV
It sounds simple : read a line, and take it appart.
For small files, a TMemo may do :
MyMemo.lines.loadfromfile('xxxxx.csv');
access the lines :
mystring:=MyMemo.lines[i];
For big files (>32k on Win95/98, a few MBytes for NT) TMemo is
useless. WinNT takes several minutes to load a 200MB file, and takes
another 200MB (glad to have them) during that process.
assignfile(f,'xxxxx.csv');
reset(f);
while (not eof(f)) do begin
readln(f,mystring);
// process the lines
closefile(f);
is much faster. A stream or blockread approach may be faster still.
The following 3 functions may help taking the string appart :
function nextcomma(s:string;i:integer):integer;
var j:integer;
begin
j:=i+1;
while (j',') do inc(j);
if (j<=length(s))and(s[j]=',') then result:=j
else result:=-1;
end;
function GetFirstV(s:string;var i:integer;):string; // first value in a line
begin
i:=nextcomma(s,1);
if (i<>-1) then result:=copy(s,1,i-1)
else result:='';
end;
function GetNextV(s:string;var i:integer;):string; // next value in a line
var j:integer;
begin
j:=i;
i:=nextcomma(s,j);
if (i<>-1) then result:=copy(s,j+1,i-j-1)
else result:=copy(s,j+1,length(s)-j);
end;
use them as :
firstvalue:=GetFirstV(mystring,i);
if (firstvalue<>'') then begin
nextvalue:=GetNextV(mystring,i);
while (nextvalue<>'') do begin // a for loop may do
nextvalue:=GetNextV(mystring,i);
..
end;
end;
Feedback is welcome
sponsored links
Delphi
home
last updated: 29.dec.99
Copyright (99,2000) Ing.Büro R.Tschaggelar