Clicky

Fortran Wiki
File_Name_Generator

File Name Generator

An example to generate

a string as file name with integer.

It was written to a lovely girl

for showing how to use “internal write”.

I gain her trust

but cannot win her heart.


    program Main

    implicit none

    ! Variables

    ! Body of Main
    write(*,*) trim(FNameGenerator("file_",".dat",11))
    write(*,*) trim(FNameGenerator("file_",".dat",11,2))
    write(*,*) trim(FNameGenerator("file_",".dat",11,3))
    
    write(*,*) "To enter, to quit."
    read(*,*)
        
    contains
    
    function FNameGenerator(head, tail, IntNum, LenLimit) result(res)
    character(*)    ::  head, tail
    integer(4)      ::  IntNum, LenLimit
    optional        ::  LenLimit
    
    character(20)   ::  fmt
    character(1000) ::  res
    integer(4)      ::  LimitUsed
    if (present(LenLimit)) then
        LimitUsed = LenLimit
    else
        LimitUsed = 7  !Maybe you only need 2 or 3.
    end if
    
    fmt = ""; res=""
    write(fmt(:),'("(i",i2.2,".",i2.2,")")') LimitUsed, LimitUsed
    write(res(:),fmt) IntNum
    res=trim(adjustL(head))//trim(adjustL(res))//trim(adjustL(tail))
    end function
    
    end program Main