Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape quotes and remove double newline in fortran write

I'm trying to output a trivial error message in Fortran90, like so:

error: failed to read '<file>'

But I cannot figure out how to produce the single quotes, escaping them leads to compilation errors. I have tried the following:

write(*, fmt="('error: failed to read: \'', a, '\'')") arg

Also, if I print the message without them:

write(*, fmt="('error: failed to read: ', a)") file

an extra newline (i.e. two in total) is produced on the command line. I obtain arg by executing call getarg(1, arg), maybe that has something to do with it.

Here is a minimal working example which demonstrates the newline problem:

program foo                                                        
    character(len=100) :: arg

    call getarg(1, arg)

    write(*, fmt="('error: failed to read: ', a)") arg
end program foo

I find formatted output in fortran to be very unintuitive, if someone could additionally direct me to a resource that explains this in more detail that would be great.

like image 735
Peter Avatar asked Mar 05 '23 03:03

Peter


1 Answers

It is much better, in my opinion, to not enter the printed strings into the format, as you do in C, but rather put them into the output list.

I also recommend to trim the filename trim(arg) when printing it, so that you do not print around 90 useless trailing blanks.

program foo
    implicit none                                                        
    character(len=100) :: arg

    call getarg(1, arg)

    write(*, '(*(a))') "error: failed to read: '", trim(arg), "'"
end program foo

That way you do not need one outer layer of quotes that quote the format string itself.

Even inside any string you can repeat a quote to put it into the string, i.e. '''' (see Difference between double and single quotation marks in fortran?)

BTW, standard Fortran 2003 has subroutine GET_COMMAND_ARGUMENT instead of GETARG.

like image 134
Vladimir F Героям слава Avatar answered Mar 24 '23 06:03

Vladimir F Героям слава