program dataread
implicit none
integer::I,J,K
integer::Mx1,Mx2,N1,N2
character(len=20)::file1,file2,file3
character ans
real,dimension(:),allocatable::data1,data2
file1="1.txt"
file2="2.txt"
file3="3.txt"
open(11,file= trim(file1),status="old",err=998)
open(12,file= trim(file2),status="old",err=998)
open(13,file= trim(file3))
Mx1=0
N1=0
do
read(11,*,end=22)I
write(*,*)"1",I
if (Mx1 N1=N1+1
enddo
22 Mx2=0
N2=0
do
read(12,*,end=23)I
write(*,*)"2",I
if (Mx2 N2=N2+1
enddo
if(N1.ne.N2) then
write(*,*)"Data Numbers in two files are not the same, do you still wanna continue?(Y/N)"
read(*,*)ans
if(ans.eq."N") stop " Sorry, merge data can not be finished."
endif
23 allocate(data1(N1),data2(N2))
rewind 11
rewind 12
do I=1,min(N1,N2)
read(11,*)J,data1(I)
read(12,*)K,data2(I)
if(J.ne.K) then
write(*,*) "Warning, numbers are not the same in two files"
endif
write(13,"(2F10.3)")data1(I),data2(I)
enddo
goto 999
998 stop "File can not be found!"
999 stop "Normal End"
end
由于不是很了解数据到底是什么样的,所以在写程序的时候并没有前面编号不一致的情况,但是扩展性还是留下了,那个Mx1和Mx2目的就是为了防止楼主万一要拓展,要求用编号控制对应的数字或者编号不是按照对应顺序的。反正这个代码是基本能实现楼主的要求了。如果1和2文件中的数字个数不一致的话,程序会提醒并询问是否继续,要是继续的话就按照个数最小的那个文件个数来排序。
Program www_fcode_cn
Implicit None
Real :: a , b , c
Integer :: ierr
Open( 12 , File = "1.txt" )
Open( 13 , File = "2.txt" )
Open( 14 , File = "3.txt" )
Do
Read( 12 , * , iostat = ierr ) a , b
if ( ierr /= 0 ) Exit
Read( 13 , * , iostat = ierr ) a , c
if ( ierr /= 0 ) Exit
write( 14 , * ) b , c
End Do
Close( 12 )
Close( 13 )
Close( 14 )
End Program www_fcode_cn