home *** CD-ROM | disk | FTP | other *** search
- /* Some constants for exceptions (ERR_NONE is zero: no error) */
- ENUM ERR_NONE, ERR_LEN, ERR_NEW, ERR_OPEN, ERR_READ
-
- /* Make some exceptions automatic */
- RAISE ERR_LEN IF FileLength()<=0,
- ERR_NEW IF New()=NIL,
- ERR_OPEN IF Open()=NIL
-
- PROC main() HANDLE
- /* Note the careful initialisation of buffer and filehandle */
- DEF buffer=NIL, filehandle=NIL, len, filename
- filename:='datafile'
- /* Get the length of data in the file */
- len:=FileLength(filename)
- /* Allocate just enough room for the data + a terminating NIL */
- buffer:=New(len+1)
- filehandle:=Open(filename, OLDFILE)
- /* Read whole file, checking amount read */
- IF len<>Read(filehandle, buffer, len) THEN Raise(ERR_READ)
- /* Terminate buffer with a NIL just in case... */
- buffer[len]:=NIL
- process_buffer(buffer, len)
- EXCEPT DO
- /* Both of these are safe thanks to the initialisations */
- IF buffer THEN Dispose(buffer)
- IF filehandle THEN Close(filehandle)
- /* Report error (if there was one) */
- SELECT exception
- CASE ERR_LEN; WriteF('Error: "\s" is an empty file\n', filename)
- CASE ERR_NEW; WriteF('Error: Insufficient memory to load file\n')
- CASE ERR_OPEN; WriteF('Error: Failed to open "\s"\n', filename)
- CASE ERR_READ; WriteF('Error: File reading error\n')
- ENDSELECT
- 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
-