Convert integers to strings to create output filenames at run time

前端 未结 9 2112
小鲜肉
小鲜肉 2020-11-22 02:47

I have a program in Fortran that saves the results to a file. At the moment I open the file using

OPEN (1, FILE = \'Output.TXT\')

However,

9条回答
  •  离开以前
    2020-11-22 03:30

    I've tried @Alejandro and @user2361779 already but it gives me an unsatisfied result such as file 1.txt or file1 .txt instead of file1.txt. However i find the better solution:

    ...
    integer :: i
    character(len=5) :: char_i     ! use your maximum expected len
    character(len=32) :: filename
    
    write(char_i, '(I5)') i        ! convert integer to char
    write(filename, '("path/to/file/", A, ".dat")') trim(adjustl(char_i))
    ...
    

    Explanation:

    e.g. set i = 10 and write(char_i, '(I5)') i

    char_i                gives  "   10" ! this is original value of char_i
    
    adjustl(char_i)       gives  "10   " ! adjust char_i to the left
    
    trim(adjustl(char_i)) gives  "10"    ! adjust char_i to the left then remove blank space on the right
    

    I think this is a simplest solution that give you a dynamical length filename without any legacy blank spaces from integer to string conversion process.

提交回复
热议问题