Return string of characters of unknown length in fortran

Apologies for the pretty simple question, I just can't find ANY good fortran docs.

I am trying to write a function that reads from one, truncates the output and adds a null terminator, something like:

character(*) function readCString()
  character*512 str
  read(1, *) str
  readCString = TRIM(str)//char(0)
  return
end function readCString

However, I KNOW that this has not yet worked. Recently, segmentation flaws have not been my friend. Without "character (*)" before the function keyword, it will not compile, and with any value instead of a star, it also breaks, most likely because:

TRIM(str)//char(0)

not the same length as the number I put in place of a star. I am very new to fortran, but trying to associate some fortran code with C (hence the null terminator).

Thanks for any help.

+3
1

() . character (star) - . (*) , , . , . . Fortran 2003 , . - .

, Fortran:

module test_func_mod
contains
function readCString()
  use iso_c_binding
  character (kind=c_char, len=512)  :: readCString
  character (kind=c_char, len=511) :: str
  read(1, *) str
  readCString = TRIM(str) // C_NULL_CHAR
  return
end function readCString

end module test_func_mod

program test

use test_func_mod

open (unit=1, file="temp.txt")
write (*, *) readCString()

end program test

Fortran C, ISO C. , , Fortran C , C. , , . Fortran 2003, . , .. ISO C . , (Fortran, C ) stackoverflow, .

+7

Source: https://habr.com/ru/post/1752292/


All Articles