For Programmers: Free Programming Magazines  


Home > Archive > Prolog > December 2004 > How not to read from a file?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author How not to read from a file?
Konrad Den Ende

2004-11-07, 8:56 am

I have this code that will read a file and return a list
of strings for me. This part works very nice. The issue
is that after i have got the list i will get an error if i
go "next". I'd expect the stream to be closed, hence
not producing any errors. Any suggestions?

I dislike posting large source code pieces so i've tried
to strip it down. If i have omitted something vital i do
appologize deeply.



% here's the fun part

goAheadList(File, WordList) :-
open(File, read, OS),
readList(OS, WordList),
close(OS).

readList(OS, []) :- at_end_of_stream(OS).

readList(OS, WordList) :-
readWord(OS, Word),
readList(OS, WordRest),
WordList = [Word|WordRest].

readWord(InStream,Chars) :-
get0(InStream,Char),
checkCharAndReadRest(Char,Chars,InStream
).

checkCharAndReadRest(10,[],_) :- !.
checkCharAndReadRest(32,[],_) :- !.
checkCharAndReadRest(-1,[],_) :- !.
checkCharAndReadRest(end_of_file,[],_) :- !.
checkCharAndReadRest(Char,[Char|Chars],I
nStream) :-
get0(InStream,NextChar),
checkCharAndReadRest(NextChar,Chars,InSt
ream).


--

Kindly
Konrad
---------------------------------------------------
May all spammers die an agonizing death; have no burial places;
their souls be chased by demons in Gehenna from one room to
another for all eternity and more.

Sleep - thing used by ineffective people
as a substitute for coffee

Ambition - a poor excuse for not having
enough sense to be lazy
---------------------------------------------------
vannoord@let.rug.nl

2004-11-07, 8:56 am

Konrad Den Ende <tmp1@viltersten.com> wrote:
> The issue
> is that after i have got the list i will get an error if i
> go "next". I'd expect the stream to be closed, hence
> not producing any errors. Any suggestions?


> goAheadList(File, WordList) :-
> open(File, read, OS),
> readList(OS, WordList),
> close(OS).


> readList(OS, []) :- at_end_of_stream(OS).


> readList(OS, WordList) :-
> readWord(OS, Word),
> readList(OS, WordRest),
> WordList = [Word|WordRest].


the second rule for readList applies even if you are at
the end of the stream. So upon backtracking it will attempt
to read from a closed stream.

Gj

PredAlien

2004-12-07, 8:57 pm

how do you do that for integers instead of chars?

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com