Read a file line by line
Problem. Unix/Linux systems are heavily based in text files. In particular, a record in a Unix file is identified by a text line, which is a character sequence ending with LineFeed. We would like to read lines from a text file, for example a log file, what is the right way to do it? Consider always the log writing process can happen anytime, even when we are reading and we can't assume we have permission to lock the file when we are reading from it.
Solution. In the week ending 22-Oct-2021 I [NM] tried to use the StandardFileStream>>upTo:
method. It was a disaster. This method does not do what we want out of the box and it is in the ANSI standard, it is not a good idea to change it. We added a new method to Cuis to cope with this task on 27-Oct. See StandardFileStream>>upTo:delimiterIsTerminator:
. When delimiterIsTerminator
is set to true
the method is perfect for reading log files and makes the task very easy and error free. Please see the test methods in package BaseImageTests
for further details and comments.
Example-1
" . create a file near the Image for tests and put in a fist line " fw _ 'tmp.txt' asFileEntry . fw fileContents: 'line-1', (Character lf) asString . ". open the reader stream and read up to when you find something " rs _ 'tmp.txt' asFileEntry readStream. rs upTo: (Character newLineCharacter) delimiterIsTerminator: true. "=> 'line-1 ' " rs upTo: (Character newLineCharacter) delimiterIsTerminator: true. "=> nil " ". add a line to the file " fw appendContents: 'line-2', (Character lf) asString . ". and you will get it in the reader stream " rs upTo: (Character newLineCharacter) delimiterIsTerminator: true. "=> 'line-2 ' " ". remember to close the stream " rs close.
Dr. Nicola Mingotti started this page on 22-Oct-2021. Last updated 27-Oct-2021.