2015-11-19 54 views
1

在我的代碼中,我希望能夠將某些數據寫入文件,然後寫入寫入文件頂部的條目數。Fortran:格式化寫入特定行

open(unit = 107, file = '/.data', access = 'direct', status = 'replace', recl = 200,& 
form = 'formatted') 
linecounter = 0 
do i = 1, N 
    do j = 1, 4 
     write(107, '(I3)', rec = linecounter + 1) [some data(i, j)] 
     linecounter = linecounter + 1 
    end do 
end do 
do i = 1, 2*N 
    do k = 1, 2 
     do j = 1, 4 
      if ([some condition]) then 
      write(107, '(I3)', rec = linecounter + 1) [some data(i, j, k)] 
      linecounter = linecounter + 1 
      end if 
     end do 
    end do 
end do 
write(107, '(I4)', rec = 1) linecounter 
close(107) 

這個編譯但它不工作;寫入我的文件的唯一東西是正確的行號。如果我刪除了這一行,寫入文件的唯一事情就是1

+0

看看這個http://stackoverflow.com/a/29708659/1004168 – agentp

+0

你需要explitly填寫(空白墊)每個200個字符記錄,包括明確添加適當的行結束代碼。 – agentp

回答

1

,如果你只需要直接覆蓋,你可以像這樣的第一行:

implicit none 
    integer i,j 
    open(20,file='test') ! open to write actual data sequential access. 
    write(20,'(16a)')(' ',i=1,16) ! placeholder for header 
    do i=1,10 
    write(20,*)(j,j=1,i) ! arbitrary data, different lengths each line 
    enddo   
    close(20) 
    ! reopen direct access 
    open(20,file='test',form='formatted',access='direct',recl=16) 
    ! note recl is exactly the placeholder length. 
    write(20,'(2i8)',rec=1)0,42 
    ! take care to write exactly recl bytes - some compilers will blank pad 
    ! for you if you write less than a full record, but i wouldn't count on it. 
    close(20) 
    end 

照顧我認爲recl的含義不是標準。根據您的編譯器有時單位是4個字節。 (也許它總是1個字節的格式化訪問。也許一些標準大師可以發表評論。)

+0

@VladimirF我同意,但從我可以告訴'inquire'只能告訴無格式記錄的長度。 (它實際上是一個4字節的單元'未格式化的「和1個字節的'格式化單元')。如果你知道「詢問」咒語,表明我想看。 – agentp

+0

你說得對。它實際上可以是格式化的字符數。更好地檢查標準。 –