Search code examples
fortran

Writing a lot of values to a file with the same format and line breaks


I want to write multiple values to a file, all of the same type (float). This is generally pretty easy to write as I can put '20(f10.3,1x)' as the format to write all the values. The problem here is that I want line breaks in between certain values. An example of what I want to achieve is:

write(output_unit,*format goes here*) a1, a2, *line break*, a3, a4,&
      & a5, *line break*, a6, a7, a8, a9, a10, a11, *line break*, a12,&
      & a13, *line break*, ...

All the variables here are of the same format, but the line breaks appear at different locations. Note that 'a' here is not an array. They are all separate variables.

Is there a way to add line breaks either in the format section without having to repeat the '(f10.3,1x)' 20 times?

I know I can define the format separately as

10 format(f10.3,1x)

but can I use something like

write(output_unit,2(10),'/',3(10),'/',...)

Solution

  • It is not possible to build up a single input/output format using expressions of labelled format statements (as you are trying with 2(10),'/',3(10),'/',...). It is possible to build up one with character expressions, but, gosh, wouldn't that be horrible?

    Instead, you can intersperse the slash edit descriptor in a more explicitly written way using the same repeat count specifier:

    print '(2(f10.3,1x),/,3(f10.3,1x))', a1, a2, a3, a4, a5
    

    That is, you write out the fundamental unit ((f10.3,1x)) each time, rather than referencing a labelled format statement.

    This is less ugly than a large character expression, but ugly it remains. Your structure is much more clearly shown using multiple output statements:

    character(*), parameter :: fmt='(*(f10.3,1x))'
    
    print fmt, a1, a2
    print fmt, a3, a4, a5
    

    Yes, one can also use generalized editing (Gw.d) with a new line in the output list, but that also obfuscates the structure of your output (and note also that there's no Gw.d that behaves exactly like f10.3).