File Output using Gforth

Posted by sheepez on Stack Overflow See other posts from Stack Overflow or by sheepez
Published on 2010-12-18T22:15:14Z Indexed on 2010/12/26 17:54 UTC
Read the original article Hit count: 150

Filed under:

As a first project I have been writing a short program to render the Mandelbrot fractal. I have got to the point of trying to output my results to a file ( e.g. .bmp or .ppm ) and got stuck.

I have not really found any examples of exactly what I am trying to do, but I have found two examples of code to copy from one file to another.

The examples in the Gforth documentation ( Section 3.27 ) did not work for me ( winXP ) in fact they seemed to open and create files but not write to files properly.

This is the Gforth documentation example that copies the contents of one file to another:

0 Value fd-in
0 Value fd-out
: open-input ( addr u -- )  r/o open-file throw to fd-in ;
: open-output ( addr u -- )  w/o create-file throw to fd-out ;

s"" open-input
s" foo.out" open-output

: copy-file ( -- )
      line-buffer max-line fd-in read-line throw
      line-buffer swap fd-out write-line throw
  repeat ;

I found this example ( ) which does work. The main problem is that I can't isolate the part that writes to a file and have it still work. The main confusion is that >r doesn't seem to consume TOS as I might expect.

: copy-file2 ( a1 n1 a2 n2 -- )
    r/o open-file throw >r
    w/o create-file throw r>
        pad maxstring  2 pick  read-file throw
    ?dup while
        pad swap  3 pick  write-file throw
    close-file throw
    close-file throw ;

\ Invoke it like this:
    s" output.txt" s" input.txt" copy-file

I would be very grateful if someone could explain exactly how the open, create read and write -file words actually work, as my investigation keeps resulting in somewhat bizarre stacks.

Any clues as to why the Gforth examples do not work might help too.

In summary, I want to output from Gforth to a file and so far have been thwarted. Can anyone offer any help?

Thank you Vijay, I think that I understand the example that you gave. However when I try to use something like this ( which I think is similar ):

0 value test-file

: write-test
    s" testfile.out" w/o create-file throw to test-file
    s" test text" test-file write-line ;

I get ok but nothing is put into the file, have I made a mistake?

It seems that the problem was due to not flushing the relevant buffers or explicitly closing the file. Adding something like

test-file flush-file throw


test-file close-file throw

between write-line and ; makes it work.

Thanks again Vijay for helping.

© Stack Overflow or respective owner

Related posts about file-io

Related posts about bitmap