Claire
Claire

Reputation: 3

Reading a text file as a input and then writing text files with the data in 2D matrices as output

I am the real novice in FORTRAN90, of course in any other programming language. However, I need to make a program for my work. So I am asking any comment from anybody. Thanks in advance.

From now on, I will explain my problem. The original data is just following as;

15 1r 2 1r 70 22r 2 2r 15 1r 2 1r 8 8r 15 1 3r

This is could be written again in another way like below;

15 15 2 2 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 70 2 2 2 15 15 2 2 
8 8 8 8 8 8 8 8 8 15 1 1 1 1

So the total number of data elements in the above example can be counted 48. The total number of the original data is 12,113,640. And then the original data was made of 220(z) slices of 322(x) x 171(y). Each slices has 55,062 of elements.

If it is possible, just like the way of count of the element number, the program count by 55,062 elements and then make output file(txt) and then totally 220 slices of the data should be 2D array.

So I have to extract 220 slices from the one whole data file. And also the data should be 2D array in each slice.

Upvotes: 0

Views: 326

Answers (1)

cup
cup

Reputation: 8267

It will be something like this - I assume you know how to read lines from the file

program main
   character(len=120):: compressed
   character ch
   integer value, rval, repeat, ix, complen

   ! Pretend this is the line read from the file
   compressed = '15 1r 2 1r 70 22r 2 2r 15 1r 2 1r 8 8r 15 1 3r'

   complen = len(trim(compressed))
   ix = 1
   do while (ix .lt. complen)
      ! Skip spaces
      do
         ch = compressed(ix:ix)
         if (ch .ne. ' ') exit
         ix = ix + 1
      end do

      ! Extract the number
      value = 0
      do
         ch = compressed(ix:ix)
         if (ch .ge. '0' .and. ch .le. '9') then
            value = value * 10 + ichar(ch) - ichar('0')
         else
            exit
         end if
         ix = ix + 1
         if (ix .gt. complen) exit
      end do

      ! is it a repeater
      repeat = 1
      if (ch .eq. 'r') then
         ! reduce by 1 since one has already been printed
         repeat = value  - 1
         ix = ix + 1
      else
         rval = value
      end if

      ! assume there won't be more than 100 repeats
      write(*, '(100I3)', advance='no') (rval, ii = 1, repeat)
   end do
   stop
end program

Upvotes: 0

Related Questions