Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

open a file from its name

Status
Not open for further replies.

j0zn

Programmer
Jul 19, 2013
36
BR
I need to modify the following program to allow the user try 3 attempts to specify the name of a file that should be open. If happen any fail during the two attempts the program should write "The file no exist. Try again.",but in case to happen the third attempt the program should write " file no exist. Program finished."






PROGRAM open_old_file_verify
!Example of use of IOSTAT to verity
!the sucessful of comand OPEN

IMPLICIT none
CHARACTER(len=80) :: file_name, &
first_word
INTEGER, PARAMETER :: &
input_unit = 7, ok = 0
INTEGER :: situation_open

!Ask for the user write the name of a file
PRINT *, "Write the name of file white would be readed"
READ *, file_name

! use IOSTAT to see if OPEN worked
OPEN(unit=input_unit, &
file=file_name, status="old" ,&
iostat=situation_open )

IF( situation_open == ok ) THEN
! See what is inside the file
READ( unit=input_unit, fmt=* )&
first_word

PRINT *,
PRINT *, " The first work on file is : "
PRINT *, first_word

ELSE

PRINT *
PRINT *, " can not open the file"
END IF

END PROGRAM open_old_file_verify
 
You need a do-loop that would be done up to 3 times
Inside this loop, you need to place your PRINT, READ and OPEN statements
Then, you need an IF statement, still inside the loop, to test if the OPEN statement worked or not
If it did, you may EXIT the do loop; if it did not, you CYCLE back to the beginning of it.

One you are out of the loop, you can proceed to inspect the file with the certainty that it is there...no need for another IF statement, etc.

Needless to say, I could written all this in less words that it takes to explain...but the point is that you need to learn to google and write your own program...in particular, google the words in uppercase, if you don't already know about them.
 
I tryed a lot using CYRCLE function with the program but always got a error of compilation. Please, show me how to use cyrcle function in situation like this. I have never used cyrcle function, please someone explain me where and when I should use it (if possible with example).

Thanks in advance!
 
Cycle is not a function, it is a keyword: not a reserved word. Fortran does not have reserved words. Here is an example to illustrate its use
Code:
do ii = 1,6
   ! Skip even numbers
   if (mod(ii,2) .eq. 0) cycle
   ! Terminate when counter hits 5
   if (ii .eq. 5) exit
   print *, ii
end do
print *, 'out of loop'
What you will get is
Code:
1
3
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top