Fortran runtime error end of file

I have recently learned how to work with basic files in Fortran and I assumed it was as simple as: open(unit=10,file="data.dat") read(10,*) some_variable, somevar2 close(10) So I can't understa...

I have recently learned how to work with basic files in Fortran
and I assumed it was as simple as:

open(unit=10,file="data.dat")
read(10,*) some_variable, somevar2
close(10) 

So I can’t understand why this function I wrote is not working.
It compiles fine but when I run it it prints:

fortran runtime error:end of file

Code:

Function Load_Names()

character(len=30) :: Staff_Name(65)
integer :: i = 1

open(unit=10, file="Staff_Names.txt")

do while(i < 65)

read(10,*) Staff_Name(i)
print*, Staff_Name(i)
i = i + 1

end do

close(10)
end Function Load_Names

I am using Fortran 2008 with gfortran.

BSMP's user avatar

BSMP

4,4678 gold badges35 silver badges44 bronze badges

asked Mar 22, 2014 at 22:09

user3444034's user avatar

1

A common reason for the error you report is that the program doesn’t find the file it is trying to open. Sometimes your assumptions about the directory in which the program looks for files at run-time will be wrong.

Try:

  • using the err= option in the open statement to write code to deal gracefully with a missing file; without this the program crashes, as you have observed;

or

  • using the inquire statement to figure out whether the file exists where your program is looking for it.

answered Mar 22, 2014 at 22:51

High Performance Mark's user avatar

1

You can check when a file has ended. It is done with the option IOSTAT for read statement.
Try:

Function Load_Names()

character(len=30) :: Staff_Name(65)
integer :: i = 1
integer :: iostat

open(unit=10, file="Staff_Names.txt")

do while(i < 65)
  read(10,*, IOSTAT=iostat) Staff_Name(i)
  if( iostat < 0 )then
   write(6,'(A)') 'Warning: File containts less than 65 entries'
   exit
  else if( iostat > 0 )then
   write(6,'(A)') 'Error: error reading file'
   stop
  end if
  print*, Staff_Name(i)
  i = i + 1
end do

close(10)
end Function Load_Names

answered Mar 24, 2014 at 13:45

Alfonso Sancho's user avatar

Using Fortran 2003 standard, one can do the following to check if the end of file is reached:

    use :: iso_fortran_env

    character(len=1024) :: line
    integer :: u1,stat

    open (newunit=u1,action='read',file='input.dat',status='old')

ef: do
      read(u1,'A',iostat=stat) line
      if (stat == iostat_end) exit ef ! end of file
      ...
    end do ef
    close(u1)

answered Jan 30, 2016 at 2:57

Amir's user avatar

AmirAmir

3152 silver badges11 bronze badges

Thanks for all your help i did fix the code:

Function Load_Names(Staff_Name(65))!Loads Staff Names

    character(len=30) :: Staff_Name(65)
    integer :: i = 1

    open(unit=10, file="Staff_Names.txt", status='old', action='read')!opens file for reading

    do while(i < 66)!Sets Set_Name() equal to the file one string at a time

        read(10,*,end=100) Staff_Name(i)
        i = i + 1

    end do 
    100 close(10)!closes file
    return!returns Value
end Function Load_Names

I needed to change read(10,*) to read(10,*,END=100)
so it knew what to do when it came to the end the file
as it was in a loop I assume.

trincot's user avatar

trincot

297k33 gold badges237 silver badges276 bronze badges

answered Mar 24, 2014 at 17:07

user3444034's user avatar

user3444034user3444034

1011 gold badge1 silver badge3 bronze badges

Then your problem was that your file was a row vector, and it was likely
giving you this error immediately after reading the first element, as @M.S.B. was suggesting.

If you have a file with a NxM matrix and you read it in this way (F77):

DO i=1,N
  DO j=1,M
     READ(UNIT,*) Matrix(i,j)
  ENDDO
ENDDO

it will load the first column of your file in the first row of your matrix and will give you an error as soon as it reaches the end of the file’s first column, because the loop enforces it to read further lines and there are no more lines (if N<M when j=N+1 for example). To read the different columns you should use an implicit loop, which is why your solution worked:

DO i=1,N
    READ(UNIT,*) (Matrix(i,j), j=1,M)     
ENDDO

answered Jul 23, 2018 at 19:01

Alf Pascu's user avatar

Alf PascuAlf Pascu

3453 silver badges11 bronze badges

I am using GNU Fortran 5.4.0 on the Ubuntu system 16.04. Please check your file if it is the right one you are looking for, because sometimes files of the same name are confusing, and maybe one of them is blank. As you may check the file path if it is in the same working directory.

answered Feb 10, 2020 at 14:11

EnthusiastiC's user avatar

0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

1

Не читаются данные из файла

05.09.2015, 23:41. Показов 6681. Ответов 32


Всем привет. Такая проблема:
надо считать из текстового документа некоторые числа. Использую OPEN и READ. Файл открывается, но оттуда ничего считаться не может! Думаю проблема в формате текстового документа. Пишет: RUNTIME ERROR. END OF FILE.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



6513 / 4646 / 1932

Регистрация: 02.02.2014

Сообщений: 12,478

06.09.2015, 08:43

2

покажите свой код и файл, с которого хотите читать…



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

33878 / 18905 / 3981

Регистрация: 12.02.2012

Сообщений: 31,695

Записей в блоге: 13

06.09.2015, 09:35

3

или хотя бы оператор чтения



0



andreee

0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

06.09.2015, 10:43

 [ТС]

4

Вот код:

Fortran
1
2
3
4
5
6
         PROGRAM S5
C     =======================================================
      IMPLICIT REAL*8 (A-H,O-Z)
      OPEN(20,FILE='rmax.txt')
      READ(20,*) aa
      end

текстовый файл rmax.txt состоит из одной строки:

1.d0

Добавлено через 1 минуту
То есть видно, что проблема принципиальная! Текстовый файл лежит в той же папке, что и всё остальное.



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

33878 / 18905 / 3981

Регистрация: 12.02.2012

Сообщений: 31,695

Записей в блоге: 13

06.09.2015, 10:45

5

Цитата
Сообщение от andreee
Посмотреть сообщение

текстовый файл rmax.txt состоит из одной строки:

— тогда возможно, что у строки нет признака конца. Поставь курсор после d0, нажми Enter, сохрани и попробуй еще раз.



0



6513 / 4646 / 1932

Регистрация: 02.02.2014

Сообщений: 12,478

06.09.2015, 10:47

6

все правильно читает, без ошибок..

Кликните здесь для просмотра всего текста

Не читаются данные из файла

Цитата
Сообщение от Catstail
Посмотреть сообщение

у строки нет признака конца.

промоделировала оба случая, оба работают…

работаю в Force 2.0… это я так, на всякий случай



0



0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

06.09.2015, 11:14

 [ТС]

7

Люди, я поставил и ENTER в конце строки. И не ставил, И всё то же самое — не работает, пишет
At line 14 of file C:Fortranshe5.f (unit = 20, file = ‘err.txt’)
Fortran runtime error: End of file

Krasme, У меня тоже Force 2.0



0



6513 / 4646 / 1932

Регистрация: 02.02.2014

Сообщений: 12,478

06.09.2015, 11:30

8

так вы нам не тот код дали.. ошибка-то в другом файле… и на 14-ой строке кода…



0



0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

06.09.2015, 11:38

 [ТС]

9

Krasme, это тот код, файл я поменял. А строки пустые просто есть.



0



6513 / 4646 / 1932

Регистрация: 02.02.2014

Сообщений: 12,478

06.09.2015, 11:44

10

Цитата
Сообщение от andreee
Посмотреть сообщение

At line 14 of file C:Fortranshe5.f (unit = 20, file = ‘err.txt’)

Force на пустых строках ошибку искать не будет…
тот код, что вы указали имеет всего 6 строк…



0



0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

06.09.2015, 12:26

 [ТС]

11

Krasme, как хотите, я поменял код на тот что выложил тут выше.
Вот что пишет Фортран мне в ответ:
At line 5 of file C:Fortranshe5.f (unit = 20, file = ‘rmax.txt’)
Fortran runtime error: End of file

это то же самое.



0



Krasme

06.09.2015, 12:36

Не по теме:

Цитата
Сообщение от andreee
Посмотреть сообщение

как хотите,

одолжение делаете?
я прислала скрин в доказательство, что код работает…



0



0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

06.09.2015, 12:45

 [ТС]

13

Krasme, в чем же может быть дело? У меня не работает. Как Вы создаете текстовый документ? Я с помощью блокнота, может быть в этом дело. У меня если что Windows.



0



6513 / 4646 / 1932

Регистрация: 02.02.2014

Сообщений: 12,478

06.09.2015, 12:53

14

пользуюсь Notepad++
rmax.txt



0



Catstail

Модератор

Эксперт функциональных языков программированияЭксперт Python

33878 / 18905 / 3981

Регистрация: 12.02.2012

Сообщений: 31,695

Записей в блоге: 13

06.09.2015, 13:16

15

andreee, попробуй… удалить txt-файл и проверь, какая будет ошибка. Если останется прежняя, значит файл читается из другого места.

Или еще вариант: в операторе OPEN задай точный путь:

Fortran
1
OPEN(20,FILE='c:111222rmax.txt')



0



0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

07.09.2015, 15:20

 [ТС]

16

Krasme, а при компилляции надо что-то менять в Compilation Options ?
Т. е. вот мне надо считать данные из текстового файла err.txt. Мне достаточно написать правильный код или надо еще добавить этот текстовый файл в Compilation Options ?

Добавлено через 9 минут
Catstail, пробовал убрать файл из папки. Ошибка уже другая.
Проблема именно в чтении. Я новичок, может надо добавить название текстового файла куда-нибудь в Compilation Options например? Там у меня сейчас все строки пустые.



0



andreee

0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

07.09.2015, 15:26

 [ТС]

17

Я создавал здесь предыдущий пост. Проблема в чтении данных из текстового файла — вообще не читает.
Я поставил другой компиллятор, теперь у меня Force209G995.

Вот код:

Fortran
1
2
3
4
5
6
      program ss
      implicit real*8 (a-h,o-z)
      open (1,file='err.txt')
      read(1,*) a
      write(*,*) a
      end

Вот что мне пишет:
Traceback: not available, compile with -ftrace=frame or -ftrace=full
Fortran runtime error: End of file

Добавлено через 10 минут
Сразу скажу: в COMPILATION OPTIONS строки Options и Libraries у меня пустые. Я не разбираюсь в этом еще.



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

33878 / 18905 / 3981

Регистрация: 12.02.2012

Сообщений: 31,695

Записей в блоге: 13

07.09.2015, 15:36

18

Цитата
Сообщение от andreee
Посмотреть сообщение

Я создавал здесь предыдущий пост.

— так делать не надо. Темы объединены.

Цитата
Сообщение от andreee
Посмотреть сообщение

Ошибка уже другая.

— какая?



0



0 / 0 / 0

Регистрация: 16.08.2015

Сообщений: 35

07.09.2015, 16:00

 [ТС]

19

Catstail, ошибка
At line 4 of file C:Fortranss.f (Unit 1 «err.txt»)
Traceback: not available, compile with -ftrace=frame or -ftrace=full
Fortran runtime error: End of file

Добавлено через 17 минут
Поставил опять следующую версию Force 2.0.
Теперь ошибка вот такая:
list in: end of file
apparent state: unit 1 named err.txt
last format: list io
lately reading direct formatted external IO

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.



0



Catstail

Модератор

Эксперт функциональных языков программированияЭксперт Python

33878 / 18905 / 3981

Регистрация: 12.02.2012

Сообщений: 31,695

Записей в блоге: 13

07.09.2015, 16:32

20

andreee, это именно та же ошибка! Т.е. удалил файл err.txt, а ошибка «End of file». Это значит, что программа читает не тот файл! Запиши оператор открытия так:

Fortran
1
open (1,file='C:abcdfgerr.txt')

Нужно задать полный путь к файлу. Попробуй, должно помочь.



0



INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Fortran Run time error: End of file

Fortran Run time error: End of file

(OP)

1 Sep 14 11:51

Hello, I am a new user of Fortran, I have recently been trying to use a fortran code for my simulation. I have been able to compile the code using Gfortran, however when I try to execute the programme, it shows me the following error:

At line 7271 of file epsc4.for (unit = 1, file = ‘bench_ssSS_new.sx’)
Fortran runtime error: End of file

I am not sure what that error means, the code consists of main and subroutines in file EPSC4.For

Any help or direction about the error is much appreciated.

Regards

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.
  • Forums

  • Other Sciences

  • Programming and Computer Science

Fortran (90) runtime error: End of file

  • Fortran

  • Thread starter
    Sue Parks

  • Start date
    Oct 8, 2015

  • Oct 8, 2015
  • #1
I am using fortran 90 to find the prime numbers (1-100). When I print to the console, everything works. If I try to write to an text file (.out).
This is from my command line:
Sues-MacBook-Air:FORTRAN sueparks$ gfortran PRIME.f90
Sues-MacBook-Air:FORTRAN sueparks$ ./MY_PRIME.out

PROGRAM PRIME

implicitnone

integer, PARAMETER::M=100
integer::at, found, i
logical::is_prime
integer, dimension(M)::primes! array that will hold the primes

open (1, file="MY_PRIME.out", status="unknown")


!print *, "How many primes would you like to find?"
!read *, num_primes

primes(1)=2
at =2
found =1
do
    is_prime =.true.! assume prime
   do i =1, found
       if(modulo(at, primes(i))==0)then! if divisible by any other element
            is_prime =.false.! in the array, then not prime.
           exit
       endif
   enddo
   if(is_prime)then
        found = found +1
        primes(found)= at
        print *, at
        WRITE(1,*)"THE FIRST 100 PRIME NUMBERS:" ,AT
        CLOSE(1)
   endif
    at = at +1
   if(found == M)then! stop when all primes are found
       exit
   endif
enddo

ENDPROGRAM PRIME
Last edited by a moderator: Oct 8, 2015

Answers and Replies

  • Oct 8, 2015
  • #2
I am using fortran 90 to find the prime numbers (1-100). When I print to the console, everything works. If I try to write to an text file (.out).

?
It looks like you didn’t finish the last sentence.

  • Oct 8, 2015
  • #3
You are closing the output file as soon as you find any prime, so you’ll just print one prime in your output file.

  • Oct 8, 2015
  • #4
I moved the close() function around at the end of the program and I still get the same message :

At line 32 of file PRIME.f90 (unit = 2, file = ‘fort.2’)
Fortran runtime error: End of file

  • Oct 8, 2015
  • #5
I moved the close() function around at the end of the program and I still get the same message :

At line 32 of file PRIME.f90 (unit = 2, file = ‘fort.2’)
Fortran runtime error: End of file

What does your code look like now? The error message seems to indicate that you’re working with unit 2, but your code is opening unit 1. By the way, you need to specify that you want to write to the file, something like this:

open (1, file="MY_PRIME.out", action="write")

Also, it would be good to hand-simulate what your code is doing for a few iterations. You have primes(1) set to 2. Your code should set primes(2) to 3, and primes(3) to 5.

  • Oct 8, 2015
  • #6
Try these changes:
1) Don’t use small numbers like 1 for the unit number of the output file. They usually have special meanings. Try something like 10 or larger.
2) open the file specifically for writing. (ACTION=’WRITE’)

  • Oct 8, 2015
  • #7
I did try 10, I do not think it is reading/writing for some reason

  • Oct 8, 2015
  • #8
I did try 10, I do not think it is reading/writing for some reason

Try opening it specifically for write, ACTION=’WRITE’.

  • Oct 8, 2015
  • #9
The error message is referring to a different problem. It is trying to use unit 2, and file fort.2. Could that be the unit ‘print’ needs in line 31?. It may be the monitor and the batch file can’t use it. Try some minimal simple programs just to test print and write.

  • Oct 8, 2015
  • #10
I made some adjustments:
Sues-MacBook-Air:FORTRAN sueparks$ gfortran prime.f90
Sues-MacBook-Air:FORTRAN sueparks$ ./MY_PRIME.out

./MY_PRIME.out: line 1: THE: command not found
./MY_PRIME.out: line 2: THE: command not found
./MY_PRIME.out: line 3: THE: command not found
./MY_PRIME.out: line 4: THE: command not found
./MY_PRIME.out: line 5: THE: command not found
./MY_PRIME.out: line 6: THE: command not found
./MY_PRIME.out: line 7: THE: command not found … etc

    PROGRAM PRIME

    implicit none

    integer, PARAMETER  ::  M = 100
    integer :: at, found, i
    logical :: is_prime
    integer, dimension(M) :: primes ! array that will hold the primes
  
    open (11, file = "MY_PRIME.OUT", ACTION="WRITE")

!print *, "How many primes would you like to find?"
!read *,  num_primes

    primes(1) = 2
    at = 2
    found = 1
    do
        is_prime = .true. ! assume prime
        do i = 1, found
            if (modulo(at, primes(i)) == 0) then ! if divisible by any other element
                is_prime = .false.               ! in the array, then not prime.
                exit
            end if
        end do
        if (is_prime) then
            found = found + 1
            primes(found) = at
            print *, at
            write (11,*) at
          
          
        
          
        end if
        at = at + 1
      
        if (found == M) then ! stop when all primes are found
            exit
        end if
     close(11)
    end do
  

    END PROGRAM PRIME
Last edited by a moderator: Oct 8, 2015

  • Oct 8, 2015
  • #11
I think I got it, I believe it was my commands:

Sues-MacBook-Air:FORTRAN sueparks$ gfortran prime.f90 -o MY_PRIME.out
Sues-MacBook-Air:FORTRAN sueparks$ ./MY_PRIME.out

3
5
7
11
13
17
19
23
29
31
37
41
43

P.S. is this how an array would print?

  • Oct 8, 2015
  • #12
I think I got it, I believe it was my commands:

Sues-MacBook-Air:FORTRAN sueparks$ gfortran prime.f90 -o MY_PRIME.out
Sues-MacBook-Air:FORTRAN sueparks$ ./MY_PRIME.out

3
5
7
11
13
17
19
23
29
31
37
41
43

P.S. is this how an array would print?

Your program should print 2 as the first prime. You probably have an «off by one error» AKA OBOE.

  • Oct 8, 2015
  • #13
I think I got it, I believe it was my commands:

Sues-MacBook-Air:FORTRAN sueparks$ gfortran prime.f90 -o MY_PRIME.out
Sues-MacBook-Air:FORTRAN sueparks$ ./MY_PRIME.out

Before you call this solved, there is something you should think about. I think that your print is printing to MY_PRIME.out because of the -o option and the write is also trying to write to MY_PRIME.out because of the open statement. I don’t know how that is working. It may be just luck. You should put your prints to one file and write to another file.

  • Oct 8, 2015
  • #14
Before you call this solved, there is something you should think about. I think that your print is printing to MY_PRIME.out because of the -o option and the write is also trying to write to MY_PRIME.out because of the open statement.

I don’t think this is what’s happening. The -o option specifies the name of the object file produced, in this case, the executable. It doesn’t have anything to do with what happens at runtime.

The print statement defaults to sending output to the standard output device. The write(11, …) statement sends output to the file specified in the associated open statement.

I don’t know how that is working. It may be just luck. You should put your prints to one file and write to another file.

Her intent, I believe, is to use print to send output to the monitor and write to send output to the file.

  • Oct 8, 2015
  • #15
It did both, it printed to the console and it filled the text file. They both look the same.

  • Oct 8, 2015
  • #16
So, it printed everything but 2. Let me check my loops and variables again.

  • Oct 9, 2015
  • #17
As I said in post #5,

Also, it would be good to hand-simulate what your code is doing for a few iterations. You have primes(1) set to 2. Your code should set primes(2) to 3, and primes(3) to 5.

Since you know the size of your array, you would be better off using an iterative loop (DO I = 1, N) than the plain DO loop you have as your outer loop. At any rate, check the value of your array index for the first number you print/write.

  • Oct 9, 2015
  • #18
I don’t think this is what’s happening. The -o option specifies the name of the object file produced, in this case, the executable. It doesn’t have anything to do with what happens at runtime.

Oh, that’s right. But then the write statement must be overwriting the object file. I am sure that is not what you want to do.

  • Oct 9, 2015
  • #19
Back in post #10, you compile your program for the n-th time with «gfortran prime.f90″…this produces an executable with defualt name of «a.out»; BUT, your attempted to run an executable of name «MY_PRIME.out»…which was produced in one of your previous runs and filled with lines like «THE FIRST 100…» and so, that is why the computer complains of «command not found» because «THE» is not a command.

Then, when you started to compile with ‘ -o ‘, you made the bad choice of requesting and executable with the same name as the file you chose to write from the program itself «MY_PRIME.out»…so, yes, you are replacing your program executable with a text file. The reason why this works is simpy because in order to run the program, the computer first loads it into memory, once there, it can be deleted from disk or over written, not a problem.

The reason why the 2 does not show up is because you assign that one before you enter the loop; but,the loop only prints prime numbers found during the loop itself, not before.

  • Oct 10, 2015
  • #20
@Sue Parks , You should get into the habit of using file extensions that tell you what type of file it is. Typically, the output of the compile and built should have a .EXE extension to tell you that it is an executable file ( -o MY_PRIME.EXE ). Readable text from the write statement should have a .TXT extension ( open (11, file=»MY_PRIME.TXT», ACTION=»WRITE») ).

Suggested for: Fortran (90) runtime error: End of file

  • Last Post
  • Jan 18, 2020
  • Last Post
  • Apr 1, 2019
  • Last Post
  • Mar 23, 2021
  • Last Post
  • Jul 18, 2021
  • Last Post
  • Jul 1, 2021
  • Last Post
  • Jan 10, 2021
  • Last Post
  • Nov 26, 2019
  • Last Post
  • Today, 12:16 AM
  • Last Post
  • Jan 10, 2023
  • Last Post
  • Dec 4, 2022
  • Forums

  • Other Sciences

  • Programming and Computer Science

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Freemarker template error the following has evaluated to null or missing
  • Fortran runtime error bad real number in item 1 of list input
  • Freelander 2 ошибка ограничение мощности
  • Fortran runtime error bad integer for item 1 in list input
  • Freelander 2 ошибка terrain response

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии