How to resolve the algorithm Read a file character by character/UTF8 step by step in the zkl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Read a file character by character/UTF8 step by step in the zkl programming language

Table of Contents

Problem Statement

Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files containing UTF8 encoded wide characters, returning whole characters for each consecutive read.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Read a file character by character/UTF8 step by step in the zkl programming language

Source code in the zkl programming language

fcn readUTF8c(chr,s=""){ // transform UTF-8 character stream
   s+=chr;
   try{ s.len(8); return(s) }
   catch{ if(s.len()>6) throw(__exception) } // 6 bytes max for UTF-8
   return(Void.Again,s);  // call me again with s & another character
}

fcn utf8Walker(obj){
   obj.walker(3)  // read characters
   .tweak(readUTF8c)
}

s:="-->\u20AC123";  // --> e2,82,ac,31,32,33 == -->€123
utf8Walker(s).walk().println();

w:=utf8Walker(Data(Void,s,"\n")); // Data is a byte bucket
foreach c in (utf8Walker(Data(Void,s,"\n"))){ print(c) }

utf8Walker(Data(Void,0xe2,0x82,"123456")).walk().println(); // € is short 1 byte

stream:=Data(Void,s,"\n").howza(3); // character stream
stream.pump(List,readUTF8c,"print")

File("foo.txt","rb").howza(3).pump(List,readUTF8c,"print");

  

You may also check:How to resolve the algorithm Sorting algorithms/Radix sort step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Munching squares step by step in the BASIC programming language
You may also check:How to resolve the algorithm Determine if a string is squeezable step by step in the Phix programming language
You may also check:How to resolve the algorithm Hailstone sequence step by step in the Phix programming language
You may also check:How to resolve the algorithm Narcissistic decimal number step by step in the Ksh programming language