how to get a filename in gnuforth from user input to save it

50 Views Asked by At

currently I try to add a save function to a code from gforth 0.7.3 currently the version I have works fine if savefile is already existing (filled or empty as no importance both use-case are OK)

here is the code I test to get filename & save it

27 constant ESC  \ to manage escape sequences used as coloration
0 value handle
        
: 2>str ( n1 n2--cadr u) s>d <# #s bl hold 2drop s>d #s #> ;
        
: wr ( cadr n--) handle write-line throw ;
        
: wr-slot { x y } x y sarray count ?dup if
          x y 2>str wr wr 
      else drop 
      then ;
    
: COLORIZE ESC EMIT ." [" base @ >R 0 <# #S #> type R> base ! ." m" ; \ ASCII TERMINAL
    
: getfname  ( --cadr n) type pad 64 accept pad swap ;
    
: save 31 colorize s" Save to file: " getfname  w/o open-file ?dup if 
       nip ." error" 
    else 
      to handle 0 
    then  
    if exit then ['] wr-array catch if 33 colorize s" Error while writing to file." 0 colorize error then  close ;
        \ etc...* 

I do not understand how I can modify it adding or not a new definition to permit saving on a file that doesn'exist yet / keeping possibility to save in an existing one.

I worked around without succes, for now.

1

There are 1 best solutions below

0
francois P On

In fact I just had to create file empty and then open it write/open as a buffer "fd-out"

so this part of code becomes :

0 Value fd-out \ for saving file

    : getfname  ( -- addr n) type pad 64 accept pad swap ;
    : open-output ( addr u -- )  w/o create-file throw to fd-out ;
    : open ( cadr n mode--ior) open-file ?dup if  nip 31 colorize s" Cannot open file." 0 colorize error else  to handle 0  then ;
    : close-output ( -- )  fd-out close-file throw ;
    : close ( --ior) handle close-file
      if 33 colorize s" Error while closing file." 0 colorize error then ;
    \ fix unknown filename saving by creating it empty first then writing in it
    : read s" filename ? " getfname 2dup open-output close-output ;
    : save bottom 31 colorize read w/o open if exit then ['] wr-array catch 0 colorize if 33 colorize s" Error while writing to file." 0 colorize error then  close ;