Temporary Files and Directories in Co-array Fortran
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.
We then open this file for writing and write some integer data to it.
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.
Finally, we clean up by removing both the temporary file and directory using the remove_file
and remove_dir
subroutines.
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:
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.