How to resolve the algorithm Unix/ls step by step in the Forth programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Unix/ls step by step in the Forth programming language

Table of Contents

Problem Statement

Write a program that will list everything in the current folder,   similar to:

The output must be sorted, but printing extended details and producing multi-column output is not required.

For the list of paths:

When the program is executed in   /foo,   it should print: and when the program is executed in   /foo/bar,   it should print:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Unix/ls step by step in the Forth programming language

Source code in the forth programming language

256 buffer: filename-buf
: each-filename { xt -- }  \ xt-consuming variant
  s" ." open-dir throw { d }
  begin filename-buf 256 d read-dir throw while
    filename-buf swap xt execute
  repeat  d close-dir throw ;

\ immediate variant
: each-filename[  s" ." postpone sliteral ]] open-dir throw >r begin filename-buf 256 r@ read-dir throw while filename-buf swap [[ ; immediate compile-only
: ]each-filename  ]] repeat drop r> close-dir throw [[ ; immediate compile-only

: ls ( -- )  [: cr type ;] each-filename ;


: save-string ( c-addr u -- a )
  dup 1+ allocate throw dup >r place r> ;

require ffl/car.fs
: sorted-filenames ( -- car )
  0 car-new { a }
  [: swap count rot count compare ;] a car-compare!
  each-filename[ save-string a car-insert-sorted ]each-filename
  a ;

: each-sorted-filename ( xt -- )
  sorted-filenames { a }  a car-execute  [: free throw ;] a car-execute  a car-free ;

: ls ( -- )
  [: count cr type ;] each-sorted-filename ;


  

You may also check:How to resolve the algorithm Permutations/Derangements step by step in the Acornsoft Lisp programming language
You may also check:How to resolve the algorithm Guess the number/With feedback step by step in the Swift programming language
You may also check:How to resolve the algorithm Memory allocation step by step in the Python programming language
You may also check:How to resolve the algorithm Trigonometric functions step by step in the COBOL programming language
You may also check:How to resolve the algorithm Polynomial regression step by step in the PowerShell programming language