Temporary Files and Directories in Co-array Fortran

program temporary_files_and_directories
  use, intrinsic :: iso_fortran_env
  use :: stdlib_os, only : create_temp_file, create_temp_dir, remove_file, remove_dir
  implicit none
  
  character(len=:), allocatable :: temp_file, temp_dir
  integer :: unit, io_status
  
  ! Create a temporary file
  call create_temp_file(temp_file, "sample")
  print *, "Temp file name: ", temp_file
  
  ! Open the file for writing
  open(newunit=unit, file=temp_file, status='replace', action='write', iostat=io_status)
  if (io_status /= 0) error stop "Error opening temporary file"
  
  ! Write some data to the file
  write(unit) 1, 2, 3, 4
  close(unit)
  
  ! Create a temporary directory
  call create_temp_dir(temp_dir, "sampledir")
  print *, "Temp dir name: ", temp_dir
  
  ! Clean up
  call remove_file(temp_file)
  call remove_dir(temp_dir)
end program temporary_files_and_directories

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

In this example, we’re using the stdlib_os module from the Fortran stdlib, which provides utilities for working with the operating system, including creating temporary files and directories.

We start by creating a temporary file using the create_temp_file subroutine. This creates a file with a unique name starting with the prefix “sample”. The full path of the created file is stored in the temp_file variable.

call create_temp_file(temp_file, "sample")
print *, "Temp file name: ", temp_file

We then open this file for writing and write some integer data to it.

open(newunit=unit, file=temp_file, status='replace', action='write', iostat=io_status)
if (io_status /= 0) error stop "Error opening temporary file"

write(unit) 1, 2, 3, 4
close(unit)

Next, we create a temporary directory using the create_temp_dir subroutine. This creates a directory with a unique name starting with the prefix “sampledir”. The full path of the created directory is stored in the temp_dir variable.

call create_temp_dir(temp_dir, "sampledir")
print *, "Temp dir name: ", temp_dir

Finally, we clean up by removing both the temporary file and directory using the remove_file and remove_dir subroutines.

call remove_file(temp_file)
call remove_dir(temp_dir)

This ensures that we don’t leave any unnecessary files or directories on the system after our program exits.

To compile and run this program, you would typically use a command like:

$ gfortran -o temp_files temp_files.f90 -I/path/to/stdlib/mod -L/path/to/stdlib/lib -lstdlib
$ ./temp_files
Temp file name: /tmp/sampleXXXXXX
Temp dir name: /tmp/sampledirXXXXXX

Note that the actual names of the temporary file and directory will be different each time you run the program, as they are generated to be unique.