write formatted UTF-8 text file fortran - fortran

I'm trying to write in from fortran a text file.
I did this short test program but of course it does not work, because it does not create a text file that could be readable :
PROGRAM teste
INTEGER(4) REC2,RECL1
character(20) :: charI, wanted
RECL1=10
DO REC2=1,10
OPEN(1,FILE='teste.txt',ACCESS="direct",RECL=RECL1);
write (charI, "(A5,I4)") "hello", REC2
wanted=trim(charI)
write(1,REC=REC2) wanted
close(1)
END DO
END PROGRAM teste
I read lot of different thing but it's still really unclear how it should be written.
Do I need to convert to string before writing ? if yes why ?

Try this
PROGRAM test
IMPLICIT NONE
INTEGER, PARAMETER :: ascii = selected_char_KIND ("ascii")
INTEGER, PARAMETER :: ucs4 = selected_char_KIND ('ISO_10646')
INTEGER :: ix
CHARACTER(len=5,kind=ucs4) :: greeting = ucs4_"hello"
OPEN(10,FILE='test.txt')
DO ix=1,10
WRITE (10,'(A5,I4)') greeting, ix
END DO
CLOSE(10)
END PROGRAM test
... a commentary ...
PROGRAM test
IMPLICIT NONE
All good Fortran programs include the line implicit none; the reason for this is explained in 101 Qs and As here on Stack Overflow and I won't repeat them here.
INTEGER, PARAMETER :: ascii = selected_char_KIND ("ascii")
INTEGER, PARAMETER :: ucs4 = selected_char_KIND ('ISO_10646')
The latest Fortran standard requires that compilers provide these two kinds of character. I'm honestly not sure if iso_10646 is the same as UTF-8 but if it isn't you're probably out of luck. Here, I'm defining two parameters for identifying the character kinds to use later in the program. For your purposes the first of these parameters is unnecessary but you ought to know about it too.
I suppose your compiler might support other character kinds, read the documentation.
(Aside: technically, there is a third character kind name, default. This is likely to set the character kind to either ascii or iso_10646, most likely the former, but if this is important to you check your compiler's documentation.)
INTEGER :: ix
CHARACTER(len=5,kind=ucs4) :: greeting = ucs4_"hello"
In the second of these lines I've defined a character variable with the text hello and of kind ucs4 (which, as you see above, is a local code for iso_10646). Without the prefix ucs4_ the string hello will be interpreted as being of kind default and then converted to ucs4 when stored into the variable greeting. In this case, where there is a 1:1 mapping between the (representation of) the characters in ascii and in ucs4 the prefix is strictly unnecessary but there will be other cases where it won't be.
OPEN(10,FILE='test.txt')
DO ix=1,10
WRITE (10,'(A5,I4)') greeting, ix
END DO
CLOSE(10)
I've removed all the guff about direct access and writing at particular records in a file. It's all unnecessary for what seems to be your immediate need. So this loop will write greeting (ie the ucs4 string hello) and a row index into the file test.txt 10 times.
END PROGRAM test

In your open statement you are opening a file for unformatted input/output. Because you have specified ACCESS="direct" the default is for unformatted, compared with the default as formatted when connected for sequential access.
To make the file "readable" you need to actively open for formatted access, and provide a format for the writing:
open(1,FILE='teste.txt',ACCESS="direct",RECL=RECL1, FORM='formatted')
...
write(1,fmt=...,REC=REC2) ...

Related

trying to write string in subroutine causing error

Due to some restriction on my assignment, F77 is used.
I am learning to use subroutine but I encounter error when trying to write string out.
PROGRAM test
IMPLICIT NONE
INTEGER a
CHARACTER*20 STR,str1
STR = 'Hello world'
a = 1
WRITE (*,*) a
WRITE (*,10) STR
CALL TEST(str1)
STOP
END
SUBROUTINE test(str2)
CHARACTER*20 str2
str2 = 'testing'
WRITE (*,10) STR2
RETURN
END
When trying to compile this code, it returns that 'Error: missing statement number 10'
Also, I have some other questions:
What does the *20 mean in CHARACTER*20 STR?
Is this the size of the string?
How about 10 in WRITE (*,10) STR? Is this the length of string to be written?
what does (*,*) mean in WRITE (*,*) a
As you can read for example here:
https://www.obliquity.com/computer/fortran/io.html
the second value given to write is an argument for the implicit format keyword, which is the label of a statement within the same program unit, a character expression or array containing the complete format specification, or an asterisk * for list-directed formatting.
Thus if you provide the data directly, you may want to use * there instead.
Otherwise, your program needs to have the label 10 at some line with formatting statement.
And yes, CHARACTER*20 STR means that the variable STR is of length 20, as you can read for instance here: https://www.obliquity.com/computer/fortran/datatype.html
The *20 after CHARACTER specifies the size of the CHARACTER variable (in this case 20 characters). FORTRAN doesn't use null-terminated strings like other languages, instead you have to reserve a specific number of characters. Your actual string can be shorter than the variable, but never longer.
The comma ( , ) in the write statement is used to separate the various arguments. Some versions of FORTRAN allow you to supply 'named' arguments but the default is the first argument is the file code to write to (a '*' implies the standard output). The second argument would be the line number of a FORMAT statement. There can be more arguments, you'd have to look up the specifics for the OPEN statement in your version of FORTRAN.
Some of your WRITE() statements are specifying to use the FORMAT statement found at lable '10'. But your sample doesn't provide any FORMAT statement, so this would be an error.
If you don't want to deal with a FORMAT statement, you can use an asterisk ( * ) as the second argument and then FORTRAN will use a general default format. That is what your first WRITE(,) is doing. It writes to 'stdout' using a general format.

Fortran :: Syntax error in OPEN statement at (1)

I was trying to test my cryptography algorithm by [diehard tests] (http://stat.fsu.edu/pub/diehard/), that I realized my input file must be an unformatted and direct access file.
So I tried to write a simple program in Fortran to read from a file and write it to another.
First of all, is it the only way to make an unformatted or direct access file ?
If it is so, I've got this Error
open(unit=2, file='unf.BIN',RECL=rl , form='UNFORMATTED', access='direct')
1
Error: Syntax error in OPEN statement at (1)
I use RECL because of some missing RECL parameter in Open statement errors.(Fortran 90, Compiling program: Error messages)
Here is my Fortran code:
program BinaryWriter
implicit none
integer :: i
integer :: p
open(unit=1,file='encout')
open(unit=2, file='unf.BIN',RECL=rl , form='UNFORMATTED', access='direct')
do i=1 ,256
read (8,'(i1)') p
write(*,*) p
end do
close(1)
close(2)
end program BinaryWriter
Two things:
1) Please stop using unit numbers less than 10. Virtually all modern Fortran compilers do now have the newunit identifier, which, instead of the old unit actually picks an unused value, so always use a variable there. But even if you want to use unit, set it to a value of 10 or more.
2) For direct access, the program needs the record length. So if you have access="direct", you also need an recl=<some integer value> to tell the compiler where a new record starts.
Now in your case, you have a RECL=rl entry in the open statement, but I can't see what rl is. It needs to be a positive integer.
Edit to add: As #IanH pointed out in a comment below your question, it is possible that you are using fixed form fortran. This might be caused by the file extension of your source code file being .f or .f77. In that case, you'd have to wrap your lines manually:
program dir
implicit none
integer :: rl
open(unit=20, file='delme.bin', recl=<the record length>,
& form='unformatted', access='direct')
close(20)
end program dir
Note that the & is in the 6th position of the line. Fortran 77 code usually uses a + there, but & is also compatible with newer Fortran versions, that's why I prefer it. F77 standard is just any character in that 6th spot.

Using a deferred-length character string to read user input

I would like to use deferred-length character strings in a "simple" manner to read user input. The reason that I want to do this is that I do not want to have to declare the size of a character string before knowing how large the user input will be. I know that there are "complicated" ways to do this. For example, the iso_varying_string module can be used: https://www.fortran.com/iso_varying_string.f95. Also, there is a solution here: Fortran Character Input at Undefined Length. However, I was hoping for something as simple, or almost as simple, as the following:
program main
character(len = :), allocatable :: my_string
read(*, '(a)') my_string
write(*,'(a)') my_string
print *, allocated(my_string), len(my_string)
end program
When I run this program, the output is:
./a.out
here is the user input
F 32765
Notice that there is no output from write(*,'(a)') my_string. Why?
Also, my_string has not been allocated. Why?
Why isn't this a simple feature of Fortran? Do other languages have this simple feature? Am I lacking some basic understanding about this issue in general?
vincentjs's answer isn't quite right.
Modern (2003+) Fortran does allow automatic allocation and re-allocation of strings on assignment, so a sequence of statements such as this
character(len=:), allocatable :: string
...
string = 'Hello'
write(*,*)
string = 'my friend'
write(*,*)
string = 'Hello '//string
write(*,*)
is correct and will work as expected and write out 3 strings of different lengths. At least one compiler in widespread use, the Intel Fortran compiler, does not engage 2003 semantics by default so may raise an error on trying to compile this. Refer to the documentation for the setting to use Fortran 2003.
However, this feature is not available when reading a string so you have to resort to the tried and tested (aka old-fashioned if you prefer) approach of declaring a buffer of sufficient size for any input and of then assigning the allocatable variable. Like this:
character(len=long) :: buffer
character(len=:), allocatable :: string
...
read(*,*) buffer
string = trim(buffer)
No, I don't know why the language standard forbids automatic allocation on read, just that it does.
Deferred length character is a Fortran 2003 feature. Note that many of the complicated methods linked to are written against earlier language versions.
With Fortran 2003 support, reading a complete record into a character variable is relatively straight forward. A simple example with very minimal error handling below. Such a procedure only needs to be written once, and can be customized to suit a user's particular requirements.
PROGRAM main
USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INPUT_UNIT
IMPLICIT NONE
CHARACTER(:), ALLOCATABLE :: my_string
CALL read_line(input_unit, my_string)
WRITE (*, "(A)") my_string
PRINT *, ALLOCATED(my_string), LEN(my_string)
CONTAINS
SUBROUTINE read_line(unit, line)
! The unit, connected for formatted input, to read the record from.
INTEGER, INTENT(IN) :: unit
! The contents of the record.
CHARACTER(:), INTENT(OUT), ALLOCATABLE :: line
INTEGER :: stat ! IO statement IOSTAT result.
CHARACTER(256) :: buffer ! Buffer to read a piece of the record.
INTEGER :: size ! Number of characters read from the file.
!***
line = ''
DO
READ (unit, "(A)", ADVANCE='NO', IOSTAT=stat, SIZE=size) buffer
IF (stat > 0) STOP 'Error reading file.'
line = line // buffer(:size)
! An end of record condition or end of file condition stops the loop.
IF (stat < 0) RETURN
END DO
END SUBROUTINE read_line
END PROGRAM main
Deferred length arrays are just that: deferred length. You still need to allocate the size of the array using the allocate statement before you can assign values to it. Once you allocate it, you can't change the size of the array unless you deallocate and then reallocate with a new size. That's why you're getting a debug error.
Fortran does not provide a way to dynamically resize character arrays like the std::string class does in C++, for example. In C++, you could initialize std::string var = "temp", then redefine it to var = "temporary" without any extra work, and this would be valid. This is only possible because the resizing is done behind the scenes by the functions in the std::string class (it doubles the size if the buffer limit is exceeded, which is functionally equivalent to reallocateing with a 2x bigger array).
Practically speaking, the easiest way I've found when dealing with strings in Fortran is to allocate a reasonably large character array that will fit most expected inputs. If the size of the input exceeds the buffer, then simply increase the size of your array by reallocateing with a larger size. Removing trailing white space can be done using trim.
You know that there are "complicated" ways of doing what you want. Rather than address those, I'll answer your first two "why?"s.
Unlike intrinsic assignment a read statement does not have the target variable first allocated to the correct size and type parameters for the thing coming in (if it isn't already like that). Indeed, it is a requirement that the items in an input list be allocated. Fortran 2008, 9.6.3, clearly states:
If an input item or an output item is allocatable, it shall be allocated.
This is the case whether the allocatable variable is a character with deferred length, a variable with other deferred length-type parameters, or an array.
There is another way to declare a character with deferred length: giving it the pointer attribute. This doesn't help you, though, as we also see
If an input item is a pointer, it shall be associated with a definable target ...
Why you have no output from your write statement is related to why you see that the character variable isn't allocated: you haven't followed the requirements of Fortran and so you can't expect the behaviour that isn't specified.
I'll speculate as to why this restriction is here. I see two obvious ways to relax the restriction
allow automatic allocation generally;
allow allocation of a deferred length character.
The second case would be easy:
If an input item or an output item is allocatable, it shall be allocated unless it is a scalar character variable with deferred length.
This, though, is clumsy and such special cases seem against the ethos of the standard as a whole. We'd also need a carefully thought out rule about alloction for this special case.
If we go for the general case for allocation, we'd presumably require that the unallocated effective item is the final effective item in the list:
integer, allocatable :: a(:), b(:)
character(7) :: ifile = '1 2 3 4'
read(ifile,*) a, b
and then we have to worry about
type aaargh(len)
integer, len :: len
integer, dimension(len) :: a, b
end type
type(aaargh), allocatable :: a(:)
character(9) :: ifile = '1 2 3 4 5'
read(ifile,*) a
It gets quite messy very quickly. Which seems like a lot of problems to resolve where there are ways, of varying difficulty, of solving the read problem.
Finally, I'll also note that allocation is possible during a data transfer statement. Although a variable must be allocated (as the rules are now) when appearing in input list components of an allocated variable of derived type needn't be if that effective item is processed by defined input.

Transfer integer to string

I am transfering an integer to a string using the following method
Character (len=10) :: s
Integer :: i
i = 7
Write (s, *, iostat=ios) i
However this leaves the contents of s empty. When I introduce an explicit format, s is populated as intended.
Character (len=10) :: s
Integer :: i
i = 7
Write (s, "(i3)", iostat=ios) i
It looks like the problem is related to the length of the string s because
when I use a longer length, I do get the correct number.
Character (len=25) :: s
The first lesson to take from this is: if you use the iostat= specifier, check the result. However, the behaviour of your code is seemingly not guaranteed. I'll base this part of the answer on intepreting how your compiler is taking things.
In addition to the iostat= specifier, in general you can use, as Vladimir F mentions in a comment, the iomsg= specifier to get a friendly message. [As IanH notes, the nominated variable is updated, and in particular may otherwise remain undefined, only in situations where the variable for the iostat= specifier is (or would be) set to non-zero.]
character (len=10) s
character (len=58) mesg
integer ios
write(s,*, iostat=ios, iomsg=mesg) 7
if (ios/=0) print*, ios, TRIM(mesg)
You want to check this, because you are using list-directed output. Here, the compiler is free to choose "reasonable" values for the integer edit format. It's more than likely that, for default integer kind, the field would be longer than 9 (don't forget the leading blank). Thus, it doesn't "fit" into the length-10 character record: "End of record" would be reasonable for mesg in this case.
With the explicit format I3 it fits with much to spare.
Why you see LEN_TRIM(s) as 10, is that s actually likely becomes junk.
Now, coming to the final part. It appears that your code with list-directed output is not valid. Fortran 2008 (and I presume many others) explicitly states:
On output, the output list and format specification shall not specify more characters for a record than ... the record length of an internal file.
The record length of your internal file being 10.
The usual caveats of relying on any particular behaviour hold. I'd be disappointed, though, if something dramatic happened.

pass FORTRAN READ arguments into a string

I have a string including the names of the variables I want read, and I would like to pass this string to the read function. This could allow me to change the name of the variables I read just changing the vector with the names of the variables.
An example could be:
PROGRAM test
implicit none
integer :: no, age
character(len=20) :: myname, vars
vars='no, myname, age'
read(*, '(i4,a20,i4)') vars
print*, no, myname, age
END PROGRAM test
Is this possible?
You can look into "NAMELIST" I/O, which maybe does what you're after. Often, namelist IO has various issues, and people often resort to writing their own custom IO routines anyway. But if it's enough for what you want, it's quite easy to use. E.g.
program nmltest
implicit none
real :: x
integer :: y
namelist /mynml/ x, y
x = 4711
y = 42
write(*, mynml)
end program nmltest
Fortran is a compiled language. It would be hard (to impossible) for the READ statement to extract variable addresses from the string list at run-time. That's why, as noted by janneb, Fortran provides the NAMELIST operator which became part of the language standard since Fortran 90 (some Fortran 77 also had support for namelists but it was non-standard and no compatibility was guaranteed between compilers). It is used like that:
...
NAMELIST /vars/ no, age, myname
...
READ(*, NML=vars)
...
The input should be something like this:
! Input can contain comments starting with exclamation marks
! And blank lines too
&vars
no = 12,
myname = 'sometext'/
Formatted input/output is not possible with NAMELIST though.