1

I'm trying to read a text file into an associative array. For example, 'text.txt' contains

1. ABC
2. XYZ

I'd like to read this text file and print them out such such Array[0] is 1. ABC and Array[1] is 2. XYZ

I have 6 lines of input in total!

Here is what I have right now

program readText
OPEN(1,FILE='text.txt')
    READ(1, *) A ,B, C, D, E, F
    WRITE (*, *) A,B,C,D, E ,F
CLOSE(1)
end program readText

After this i get

Error termination. Backtrace:
#0  0x10bde99ac
#1  0x10bdea645
#2  0x10bdeadd9
#3  0x10bfb3ecb
#4  0x10bfacab6
#5  0x10bfae509
#6  0x10bdddc82
#7  0x10bddde78

Hence, i am not even printing the text file to the screen. After this, I'd like to assign them into an array and print the array. Please let me know what I could do to solve this problem. Thanks!

4

1 Answer 1

1

Let me provide you an example where the content of the text file is written into a dynamic character array. If you are using FORTRAN then I highly recommend you to use explicit variable declaration. This can be forced by the command

implicit none

Otherwise you have to care about the implicit variable definition of FORTRAN, which can be found here:

Variables beginning with I .. N are INTEGER
Variables beginning with other letters are REAL

Extending your input file text.txt to 6 lines:

1. ABC
2. XYZ
3. FOO
4. BAR
5. BYE
6. CKE

Please use this program to create and fill the character array as well as to print it to standard output:

program readText
implicit none

integer :: FID = 1
character*256 :: CTMP

! 1. Assuming that no line of text.txt contains more than 256 characters
character*256, allocatable :: MY_ARRAY(:)
integer :: I = 0, IERR = 0, NUM_LINES = 0

open(unit=FID,file='text.txt')

! 2. Get number of lines
do while (IERR == 0)
  NUM_LINES = NUM_LINES + 1
  read(FID,*,iostat=IERR) CTMP
end do
NUM_LINES = NUM_LINES - 1
write(*,'(A,I0)') "Number of lines = ", NUM_LINES

! 3. Allocate array of strings
allocate(MY_ARRAY(NUM_LINES))

! 4. Read the file content
rewind(FID)
do I = 1, NUM_LINES
  read(FID,'(A)') MY_ARRAY(I)
end do

! 5. Print array to standard output
do I = 1,size(MY_ARRAY,1)
  write(*,*) trim(MY_ARRAY(I))
end do

deallocate(MY_ARRAY)
close(FID)

end program readText

The output looks like this:

Number of lines = 6
 1. ABC
 2. XYZ
 3. FOO
 4. BAR
 5. BYE
 6. CKE

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.