Re: Reading from a File



imaguest wrote:
Hi,

I am learning prolog and although It seems like I understand how to
read from a file, when I actually try, I have a number of problems.

I am trying to read(F) where F is a file, but if I have any spaces in
the File F or the text doesn't end in a period, I have problems, and
nothing is read.

i.e. a b will give me two problems, one, there is a space, and it says:
Operator Expected, also, even before I get that error, I get an error
saying: Unexpected end of file.

It seems to me that the read(F) is treating F like a prolog file, and
applying the rules to F that you would to F.pl, is that the case?

You're right.

If you want to read a stream byte-wise or character-wise, you should use get_byte/2 or get_char/2. Here is an example to copy a file to another.

copy_file(From, To) :-
        open(From, 'read', Input),
        open(To, 'write', Output),
        copy_file_contents(Input, Output),
        close(Input),
        close(Output).

copy_file_contents(Input, Output) :-
        get_byte(Input, Byte),
        (Byte =:= -1
         -> true
         ;  put_byte(Output, Byte),
            copy_file_contents(Input, Output)).

Roland
.