xiaochen 发表于 2022-9-19 16:38:13

文件数据读写

目的:把一个叫poro的文件的数据读按顺序读取出来成一维,以后就可以直接用poro(i)来表示第i个数据
问题:写完了运行后没看见数据,是空的。求指导
program shujv1
    implicit none
   integer::NxD,NyD,NzD
   integer,allocatable::poro(:)                  

   ! Local Variables
   integer::i,j,k,l         ! Counter
   integer::stat
   character::line*160
   character::key*12
    NxD=20
   NyD=30
   NzD=1
!allocate(poro(NxD*NyD*NzD))
   ! Execution Part
k=0
open(unit=4,file='.\shujv2\poro.dat',iostat=stat)
if(stat==0)then
do
read(4,'(a)',iostat=stat)line
      ! if (stat/=0)exit
         if ((line(1:2)/='--').and.(line/=' ').and.(line(1:6)/='poro'))then

k=k+1
end if
end do

!rewind(4)
allocate(poro(k))

!if(stat==0)
    do i=1,k

   read(4,*)poro(i)

   end do

! end if

do i=1,k

write(*,*)poro(i)

end do
endif
end program

fcode 发表于 2022-9-19 17:32:46

取消 if (stat/=0)exit 和 rewind(4) 的注释

xiaochen 发表于 2022-9-20 08:57:31

fcode 发表于 2022-9-19 17:32
取消 if (stat/=0)exit 和 rewind(4) 的注释

还是不太行,而且我发现我的k的值一直没变,是我的do有问题吗

fcode 发表于 2022-9-20 09:00:57

给出你要读取的文件(或部分内容)

xiaochen 发表于 2022-9-20 09:05:49

fcode 发表于 2022-9-20 09:00
给出你要读取的文件(或部分内容)

文件是dat格式的

poro
0.203
0.191
0.194
0.256
0.231
0.227
0.285
0.249
0.195
0.159
0.148
0.193
0.200
0.244
0.240
0.222
0.223
0.240

xiaochen 发表于 2022-9-20 10:28:02

我试着改简单一点,现在有数据了,但是得出的是一个-842150451*600和文件中的完全不一样
open(unit=4,file='.\poro.dat')

allocate(poro(NxD*NyD))
read(4,*)line

if ((line(1:2)/='/').and.(line/=' ').and.(line(1:6)/='poro'))then
   k=k+1
   
   read(4,*)poro
   
end if
   close(4)
   write(*,*)line
   write(*,*)poro
   end

伊芸贾 发表于 2022-9-20 11:59:54

program shujv1
implicit none
real,allocatable::poro(:)
integer::k,stat
character(len=160) :: line
open(unit=4,file='.\poro.dat',iostat=stat)
if(stat/=0) stop
k=0
Do
    read(4,'(a)',iostat=stat) line
    if (stat/=0)exit
    if ((line(1:2)/='--').and.(line/=' ').and.(line(1:6)/='poro')) k=k+1
End Do
allocate(poro(k))
rewind(4)
k = 0
Do
    read(4,'(a)',iostat=stat) line
    if (stat/=0)exit
    if ((line(1:2)/='--').and.(line/=' ').and.(line(1:6)/='poro')) then
      k = k + 1
      read(line,*,iostat=stat) poro(k)
    end if
End Do
write(*,'(f10.4)') poro
end program shujv1

xiaochen 发表于 2022-9-20 15:08:38

伊芸贾 发表于 2022-9-20 11:59
program shujv1
implicit none
real,allocatable::poro(:)


感谢大佬,可以了{:4_96:}我改了一天,谢谢谢谢
页: [1]
查看完整版本: 文件数据读写