I have a doubt about how work this simple Prolog Program that read character from a file and put these character into a list.
The code work well and is the following one:
readFile(FileInput, TextList):- open(FileInput, read, Stream),
readCharacter(Stream, TextList),
close(Stream),
!.
readCharacter(Stream,[]):- at_end_of_stream(Stream). % Exit condition
readCharacter(Stream,[Char|Tail]):- get0(Stream,Char),
readCharacter(Stream,Tail).
When readFile/2 predicate is call happens that: the input passed file is open in read mode and that file is associated with a stream.
Then call the readCharacter/2 predicate that take the Stream associated to my input file (the file to read) and the TextList that is the list where put the file content.
readCharacter/2 predicate it is divided int two cases:
1) An exit condition that use at_end_of_stream(Stream) predicate that succeeds after the last character of the Stream (so the last character in the file) is read. In this case do nothing and the readCharacter predicate end
2) The second case is this rule that add a read character and ad it to my TextList:
readCharacter(Stream,[Char|Tail]):- get0(Stream,Char),
readCharacter(Stream,Tail).
And here I have a doubt: it read a character from the Stream using get0 and put it in the head of the list (as firs element of the list)...so...why the list don't contain the reverse of the file content?
i.e.
I have a file called myFile.txt that contains this text: abc
So readCharacter first read a character from the Stream and put it in the head of the list so I have:
TextList = [a]
Then readCharacter read b character from the Stream and put it in the head of the list si I have:
TextList = [b,a]
Then readCharacter read c character from the Stream and put it in the head of the list si I have:
TextList = [c,b,a]
If so TextList should contain the reverse content of myFile.txt file but it seems to me that TextList contain the same content of myFile.txt file in the same order.
Why? What am I missing? What is wrong in my reasoning?