[m-users.] io.error type

Fabrice Nicol fabrnicol at gmail.com
Fri Feb 4 19:27:22 AEDT 2022


Hi Volker

>
> I want to read the contents of a file, using open_input,
> read_file_as_string, close_input. In case the file doesn't exist, I want to
> return an empty string. So, in case of an error, I want to determine if it's
> because the file doesn't exist.
>
> It isn't a show stopper to me, I can return "" in case of any error, but it
> isn't optimal.
>
> Cheers,
> Volker

Why do you need to test according to io.error?

io.error will only "materialize" logical failure. Which takes place 
further up in the tree.

So you just need to test against open_input out-mode argument values.

Have you tried something along these lines?


:- pred my_pred(string::in, string::out, io::di, io::uo) is det.

my_pred(InputFileName, ResultStr, !IO) :-

          (...),

           io.stderr_stream(StdErrStream, !IO),

           io.open_input(InputFileName, OpenInputResult, !IO),
(
               OpenInputResult = ok(InputStream),
               io.read_file_as_string(InputStream, ReadInputResult, !IO),
(
                   ReadInputResult = ok(InputFileString),

                   (... unify ResultStr...)

;
                   ReadInputResult = error(_, ReadInputError),
                   io.error_message(ReadInputError, ReadInputErrorMsg),
                   io.format(StdErrStream, "error reading %s: %s\n",
                       [s(InputFileName), s(ReadInputErrorMsg)], !IO),
                   io.set_exit_status(1, !IO)  % or specific value for 
ResultStr.
)
;
               OpenInputResult = error(OpenInputError),
               io.error_message(OpenInputError, OpenInputErrorMsg),
               io.format(StdErrStream, "error opening %s: %s\n",
                   [s(InputFileName), s(OpenInputErrorMsg)], !IO),
               ResultStr=""
           )


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mercurylang.org/archives/users/attachments/20220204/2ba9baf3/attachment.html>


More information about the users mailing list