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!

passing other file txt into Fortran 1

Status
Not open for further replies.

dianda

Technical User
Jun 19, 2013
3
ID
hai.. I need your help for solve this problem.. For example, I have a file with 5 number in my data.txt.. And I sum this 5 number like this code and save the output into result.txt.. If I want to sum another file into this code (not data.txt) how could I solve this problem?
program tes
integer, parameter :: N = 5
real, dimension(1:N) :: x
real :: y
open (unit=1, file='data.txt')
do i = 1,N
read (unit=1, fmt=*) x(i)
y=x(i)+y
end do
close(unit=1)
print*,'y=',y
open (unit=2, file='result.txt')
write (unit=2, fmt=*) y
close (unit=2)
end program

thank you for your help..
 
do not use files in the first place...do not open file to read, do not open file to write...instead, use re-direction

read(*,*) x(i)

write(*,*) y

then, use your program like this from the command line:

myprog < infile > outfile

where infile and outfile can be any names you need them to be
 
thank you very much.. What about if we use another file that don't have same number, maybe we have ten number in another file.. I want my program can read automatically the number of that file (N), so we don't need input manually N.. And how if I have 2 input and two output?
 
to read variable number of rows, you need to add an extra line right at the beginning of the file indicating the number of lines the follow below...then, in your program, you first this number before you enter the loop and THEN read just as many rows as necessary. If you declared an array long enough for all cases, you will be o.k.; otherwise, you need to declare it allocatable and allocate it after reading the number of rows and before the loop.

If you have 2 inputs, again, you can add another number along the very first line of the file (following number of rows) to indicate how many numbers per row (columns) to read...but then you need to read accordingly...you could declare your array allocatable and 2-dimensional...then, using the number of rows and the number of columns, you allocate it after reading first line and before the loop, then, you can read with an implied loop.

Data sample
Code:
 5 2
 1    6
 2    7
 3    8
 4    9
 5    0

Code
Code:
read(*,*) nrows, ncols
allocate(myarr(nrows,ncols))
do n = 1, nrows
    rad(*,*) (myarr(n,m),m=1,ncols)
end do

or something along those lines.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top