[mercury-users] How to write in files???

Ralph Becket rafe at cs.mu.OZ.AU
Mon Apr 26 18:12:59 AEST 2004


Stefan Hinterstoisser, Monday, 26 April 2004:
> Hi !
> 
> Have a question about files and Mercury:
> 
> How can I create (even if a file with the same name already exists -
> the file shall be make empty and then the new output shall be written
> within) a a file, write some string output in it (not in binary code)
> and then how can I close it again???  Maybe you can give me a short
> example, Thanx Stefan Hinterstoisser
> 
> PS maybe you can also give me examples about the error handling with
> files output...

Here's a simple example that opens a file and writes something to it
(untested, but if there are bugs in it they're left as an exercise for
the student :-):

:- import_module string.

main(!IO) :-
	io.open_output("MyFile.txt", Result, !IO),
	(
		Result = error(Err),
		io.write_string(io.error_message(Err) ++ "\n", IO)
	;
		Result = ok(OutStrm),
		io.write_string(OutStrm, "Hello, World!\n", !IO)
		io.close_output(OutStrm)
	).

So
- errors are reported by return code (e.g. `Result' in the call to
  `io.open_output/4') which you handle using a switch or if-then-else
- `io.open_output/4' opens a file for writing and returns an ouput
  stream handle on success (you may also want to look at
  `io.open_append/4').
- Also take a look at `io.see/4' and friends.

Cheers,
-- Ralph
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list