James
James

Reputation: 37

Automatic file and folder naming

I am a new Fortran user. I am trying to create a file name according to date and time. I only know the command for opening fie which is:

open (unit=10,file='test.txt')

I want to have a file name instead of 'test.txt' using the current date and time when program execute. If anyone can help me I will be grateful then.

Upvotes: 0

Views: 604

Answers (2)

High Performance Mark
High Performance Mark

Reputation: 78316

You can use the intrinsic subroutine date_and_time to achieve this:

module time_ftcs

contains
  function timestamp() result(str)
    implicit none
    character(len=15)                     :: str
    character(len=8)                      :: dt
    character(len=10)                     :: tm

    ! Get current time
    call date_and_time(DATE=dt, TIME=tm)  

    str = dt//'_'//tm(1:6)  ! tm(7:10) are milliseconds and decimal point

  end function timestamp
end module

program test
  use time_ftcs, only: timestamp 

  open (unit=10,file='test_'//timestamp//'.txt')
  write(10,*) 'Hello World'
  close(10)
end program

This should result in a file

$cat test_20150405_093227.txt
 Hello World

Upvotes: 0

Alexander Vogt
Alexander Vogt

Reputation: 18098

You can use date_and_time to achieve this:

module time_ftcs

contains
  function timestamp() result(str)
    implicit none
    character(len=20)                     :: str
    integer                               :: values(8)
    character(len=4)                      :: year
    character(len=2)                      :: month
    character(len=2)                      :: day, hour, minute, second
    character(len=5)                      :: zone

    ! Get current time
    call date_and_time(VALUES=values, ZONE=zone)  
    write(year,'(i4.4)')    values(1)
    write(month,'(i2.2)')   values(2)
    write(day,'(i2.2)')     values(3)
    write(hour,'(i2.2)')    values(5)
    write(minute,'(i2.2)')  values(6)
    write(second,'(i2.2)')  values(7)

    str = year//'-'//month//'-'//day//'_'&
          //hour//':'//minute//':'//second
  end function timestamp
end module

program test
  use time_ftcs, only: timestamp 

  open (unit=10,file='test'//trim(timestamp())//'.txt')
  write(10,*) 'Hello World'
  close(10)
end program

This results in a file

$cat test2015-04-05_09:32:27.txt
 Hello World

Upvotes: 2

Related Questions