- 1 year ago
Record separators in text files written by a Fortran program
Fortran programs often create text files, and the choice of record separators can affect how the files are interpreted by different systems or text editors. In Fortran, the record separator is determined by the value of the NEWUNIT
parameter in the OPEN
statement.
By default, Fortran uses the record separator appropriate for the operating system. For example:
- On Unix-like systems (including Linux and macOS), the default record separator is a newline character (
'\n'
). - On Windows systems, the default record separator is a carriage return followed by a newline (
'\r\n'
).
If you want to explicitly set the record separator, you can use the RECL
specifier in the OPEN
statement. Here's an example:
fortranPROGRAM WriteFile
CHARACTER(LEN=2) :: record_separator = '&&' ! Custom record separator
CHARACTER(LEN=50) :: message = 'Hello, World!'
INTEGER :: iunit, i
! Open the file with a custom record separator
OPEN(UNIT=iunit, FILE='output.txt', STATUS='REPLACE', ACCESS='SEQUENTIAL', &
FORM='FORMATTED', RECL=LEN(message)+LEN(record_separator))
! Write multiple lines with the custom record separator
DO i = 1, 5
WRITE(iunit, '(A)') message
WRITE(iunit, '(A)') record_separator
END DO
! Close the file
CLOSE(iunit)
END PROGRAM WriteFile
In this example, a custom record separator ('&&'
) is used, and the RECL
specifier ensures that the record size accommodates the message and the custom separator.
Keep in mind that using non-standard record separators might cause compatibility issues when the files are opened with different text editors or on different platforms. It's generally recommended to stick with the default record separators for better interoperability.