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
4,4678 gold badges35 silver badges44 bronze badges
asked Mar 22, 2014 at 22:09
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 theopen
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
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
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
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
297k33 gold badges237 silver badges276 bronze badges
answered Mar 24, 2014 at 17:07
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 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
0 / 0 / 0 Регистрация: 16.08.2015 Сообщений: 35 |
|
1 |
|
Не читаются данные из файла05.09.2015, 23:41. Показов 6681. Ответов 32
Всем привет. Такая проблема:
__________________
0 |
6513 / 4646 / 1932 Регистрация: 02.02.2014 Сообщений: 12,478 |
|
06.09.2015, 08:43 |
2 |
покажите свой код и файл, с которого хотите читать…
0 |
Модератор 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 |
|||
Вот код:
текстовый файл rmax.txt состоит из одной строки: 1.d0 Добавлено через 1 минуту
0 |
Модератор 33878 / 18905 / 3981 Регистрация: 12.02.2012 Сообщений: 31,695 Записей в блоге: 13 |
|
06.09.2015, 10:45 |
5 |
текстовый файл rmax.txt состоит из одной строки: — тогда возможно, что у строки нет признака конца. Поставь курсор после d0, нажми Enter, сохрани и попробуй еще раз.
0 |
6513 / 4646 / 1932 Регистрация: 02.02.2014 Сообщений: 12,478 |
|
06.09.2015, 10:47 |
6 |
все правильно читает, без ошибок.. Кликните здесь для просмотра всего текста
у строки нет признака конца. промоделировала оба случая, оба работают… работаю в Force 2.0… это я так, на всякий случай
0 |
0 / 0 / 0 Регистрация: 16.08.2015 Сообщений: 35 |
|
06.09.2015, 11:14 [ТС] |
7 |
Люди, я поставил и ENTER в конце строки. И не ставил, И всё то же самое — не работает, пишет 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 |
At line 14 of file C:Fortranshe5.f (unit = 20, file = ‘err.txt’) Force на пустых строках ошибку искать не будет…
0 |
0 / 0 / 0 Регистрация: 16.08.2015 Сообщений: 35 |
|
06.09.2015, 12:26 [ТС] |
11 |
Krasme, как хотите, я поменял код на тот что выложил тут выше. это то же самое.
0 |
Krasme |
06.09.2015, 12:36
|
Не по теме:
как хотите, одолжение делаете?
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++
0 |
Catstail Модератор 33878 / 18905 / 3981 Регистрация: 12.02.2012 Сообщений: 31,695 Записей в блоге: 13 |
||||
06.09.2015, 13:16 |
15 |
|||
andreee, попробуй… удалить txt-файл и проверь, какая будет ошибка. Если останется прежняя, значит файл читается из другого места. Или еще вариант: в операторе OPEN задай точный путь:
0 |
0 / 0 / 0 Регистрация: 16.08.2015 Сообщений: 35 |
|
07.09.2015, 15:20 [ТС] |
16 |
Krasme, а при компилляции надо что-то менять в Compilation Options ? Добавлено через 9 минут
0 |
andreee 0 / 0 / 0 Регистрация: 16.08.2015 Сообщений: 35 |
||||
07.09.2015, 15:26 [ТС] |
17 |
|||
Я создавал здесь предыдущий пост. Проблема в чтении данных из текстового файла — вообще не читает. Вот код:
Вот что мне пишет: Добавлено через 10 минут
0 |
Модератор 33878 / 18905 / 3981 Регистрация: 12.02.2012 Сообщений: 31,695 Записей в блоге: 13 |
|
07.09.2015, 15:36 |
18 |
Я создавал здесь предыдущий пост. — так делать не надо. Темы объединены.
Ошибка уже другая. — какая?
0 |
0 / 0 / 0 Регистрация: 16.08.2015 Сообщений: 35 |
|
07.09.2015, 16:00 [ТС] |
19 |
Catstail, ошибка Добавлено через 17 минут This application has requested the Runtime to terminate it in an unusual way.
0 |
Catstail Модератор 33878 / 18905 / 3981 Регистрация: 12.02.2012 Сообщений: 31,695 Записей в блоге: 13 |
||||
07.09.2015, 16:32 |
20 |
|||
andreee, это именно та же ошибка! Т.е. удалил файл err.txt, а ошибка «End of file». Это значит, что программа читает не тот файл! Запиши оператор открытия так:
Нужно задать полный путь к файлу. Попробуй, должно помочь.
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 fileFortran 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’) 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 SubmittedThank you for helping keep Tek-Tips Forums free from inappropriate posts. |
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:
Talk 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 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
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
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
- Oct 8, 2015
- #4
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
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
- 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
- Oct 8, 2015
- #10
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
- Oct 8, 2015
- #11
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.out3
5
7
11
13
17
19
23
29
31
37
41
43P.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
- Oct 8, 2015
- #16
- Oct 9, 2015
- #17
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
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
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