amiga-e/amigae33a/E_v3.3a/Src/Src/Guide/csv-buff.e

69 lines
2.1 KiB
Plaintext

PROC main()
DEF buffer, filehandle, len, filename
filename:='datafile'
/* Get the length of data in the file */
IF 0<(len:=FileLength(filename))
/* Allocate just enough room for the data + a terminating NIL */
IF buffer:=New(len+1)
IF filehandle:=Open(filename, OLDFILE)
/* Read whole file, checking amount read */
IF len=Read(filehandle, buffer, len)
/* Terminate buffer with a NIL just in case... */
buffer[len]:=NIL
process_buffer(buffer, len)
ELSE
WriteF('Error: File reading error\n')
ENDIF
/* If Open() succeeded then we must Close() the file */
Close(filehandle)
ELSE
WriteF('Error: Failed to open "\s"\n', filename)
ENDIF
/* Deallocate buffer (not really necessary in this example) */
Dispose(buffer)
ELSE
WriteF('Error: Insufficient memory to load file\n')
ENDIF
ELSE
WriteF('Error: "\s" is an empty file\n', filename)
ENDIF
ENDPROC
/* buffer is like a normal string since it's NIL-terminated */
PROC process_buffer(buffer, len)
DEF start=0, end
REPEAT
/* Find the index of a linefeed after the start index */
end:=InStr(buffer, '\n', start)
/* If a linefeed was found then terminate with a NIL */
IF end<>-1 THEN buffer[end]:=NIL
process_record(buffer+start)
start:=end+1
/* We've finished if at the end or no more linefeeds */
UNTIL (start>=len) OR (end=-1)
ENDPROC
PROC process_record(line)
DEF i=1, start=0, end, s
/* Show the whole line being processed */
WriteF('Processing record: "\s"\n', line)
REPEAT
/* Find the index of a comma after the start index */
end:=InStr(line, ',', start)
/* If a comma was found then terminate with a NIL */
IF end<>-1 THEN line[end]:=NIL
/* Point to the start of the field */
s:=line+start
IF s[]
/* At this point we could do something useful... */
WriteF('\t\d) "\s"\n', i, s)
ELSE
WriteF('\t\d) Empty Field\n', i)
ENDIF
/* The new start is after the end we found */
start:=end+1
INC i
/* Once a comma is not found we've finished */
UNTIL end=-1
ENDPROC