Embed Directive in Fortran

Here’s the translation of the Go code to Fortran, with explanations in Markdown format suitable for Hugo:

Our first program will demonstrate file embedding in Fortran. While Fortran doesn’t have a built-in mechanism for embedding files at compile time like Go’s //go:embed directive, we can simulate this behavior using preprocessing and including file contents as string literals.

module file_embedding
  implicit none
  
  ! Simulate file embedding by including file contents as string literals
  character(len=*), parameter :: file_string = "hello fortran"
  character(len=*), parameter :: file_byte = "hello fortran"
  
contains
  subroutine read_file(filename, content)
    character(len=*), intent(in) :: filename
    character(len=:), allocatable, intent(out) :: content
    integer :: unit, iostat, file_size
    
    open(newunit=unit, file=filename, status='old', action='read', iostat=iostat)
    if (iostat /= 0) then
      print *, "Error opening file: ", filename
      return
    end if
    
    inquire(unit=unit, size=file_size)
    allocate(character(len=file_size) :: content)
    
    read(unit, '(A)', iostat=iostat) content
    if (iostat /= 0) then
      print *, "Error reading file: ", filename
      return
    end if
    
    close(unit)
  end subroutine read_file
end module file_embedding

program main
  use file_embedding
  implicit none
  
  character(len=:), allocatable :: content1, content2
  
  ! Print out the contents of simulated embedded files
  print *, file_string
  print *, file_byte
  
  ! Retrieve some files from the folder
  call read_file("folder/file1.hash", content1)
  if (allocated(content1)) then
    print *, content1
  end if
  
  call read_file("folder/file2.hash", content2)
  if (allocated(content2)) then
    print *, content2
  end if
  
end program main

In this Fortran version, we’ve simulated file embedding by including file contents as string literals. The read_file subroutine is used to read external files at runtime, which is more typical in Fortran programs.

To run this example, you would need to create the necessary files:

$ mkdir -p folder
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash

Then compile and run the Fortran program:

$ gfortran -o embed_files embed_files.f90
$ ./embed_files
hello fortran
hello fortran
123
456

Note that Fortran doesn’t have a direct equivalent to Go’s embed directive. The approach shown here demonstrates how to include static content in the program and read files at runtime, which are common practices in Fortran programming.