[英]Fortran Reading characters from file - no output
因此,我試圖了解一些基本的fortran IO並遇到麻煩。 我寫了以下
program RFF
implicit none
! Variables
integer :: ierr
character (:), allocatable :: Filename
character (:), allocatable :: read_in
! Body of RFF
Filename = 'string_test.txt'
open(10, file=Filename, status='old', action='read',iostat=ierr) !What is iostat?
do while (ierr.eq.0) !What is this do loop doing exactly?
read(10,'(A)',iostat = ierr) read_in !What does '(A)' mean? I know it's a format descriptor, but nothing beyond that
print*, read_in !Nothing gets output to the terminal here
enddo
write(*,*) 'Press Enter to Exit'
read(*,*)
!Is deallocating dynamically allocatable strings something I should do?
deallocate(Filename)
end program RFF
我已經提供了非常簡單的文本文件,其中包含單詞“任意”,僅此而已。 當我運行程序時,沒有崩潰,但也沒有輸出到終端。 有人可以幫助我了解發生了什么嗎? 注意,我在粘貼的代碼的注釋中插入了其他一些問題。 我也想幫助他們。
謝謝
真正的問題是,在使用read
分配read_in
之前,必須先分配read_in
。 另一件事: iostat
用於指示完成狀態或可能的錯誤情況。 有關其他詳細信息,請參見代碼注釋和官方文檔(例如, 此處 )。
這是一個可行的解決方案:
program main
implicit none
character(len=20) :: read_in ! fixed-length string
character(len=:), allocatable :: word, filename ! allocatable strings
integer :: iostat_1, iostat_2 ! status indicators
integer :: lun ! file logical unit number
filename = 'read_test.txt' ! allocate on assignment
iostat_1 = 0 ! initialization
iostat_2 = 0
open(newunit=lun, file=filename, status='old', iostat=iostat_1)
if (iostat_1 == 0) then ! no error occurred
do while(iostat_2 == 0) ! continues until error/end of file
read(lun, '(a)', iostat=iostat_2) read_in
if (iostat_2 == 0) then
word = trim(read_in) ! allocate on assignment to trimmed length.
endif
enddo
if (allocated(word)) then
print *, "read_in:", read_in
print *, "len(read_in)", len(read_in)
print *, "Word:", word
print *, "len(word)=", len(word)
else
print *, "Word was not allocated!"
endif
endif
end program main
輸出示例:
read_in:arbitrary
len(read_in) 20
Word:arbitrary
len(word)= 9
您的一個代碼中有兩個問題,所以讓我首先解決它們:
什么是iostat
? iostat
是與I / O語句有關的錯誤代碼。 如果一切正常,則將其設置為0
;否則,它將具有非零值。 有關嘗試打開文件時可能出錯的示例:
什么是(A)
? -這是格式字符串。 (A)
是指任意長度的字符串。 看到這里更多信息
該代碼看起來好像應該工作,但是結果不是您期望的。 我想到了兩種可能性:
您嘗試讀取的文件不存在,或者您正在執行程序的目錄中不存在該文件,或者您沒有讀取該文件的權限。 這導致ierr
設置為非零錯誤代碼(對應於“未找到文件”)。 這導致do
循環甚至不會執行一次,因為ierr
並非從零開始。
除了iostat
之外,我建議使用更新的iomsg
語句。 iomsg
是一個字符串,對應於人們對於錯誤原因的可讀解釋。
character(len=100) :: iomsg <snip> open(10, file=Filename, status='old', action='read',iostat=ierr, iomsg=iomsg) if (ierr /= 0) then print*, "Error opening file " // trim(Filename) print*, iomsg STOP 1 end if
該文件存在,但為空。 這將導致不打印任何內容。 只需檢查以確保文件中沒有任何更改。
提示, iostat
和iomsg
在所有文件I / O操作中都可用,因此也可以進行read
, write
甚至close
。 使用它們不會有傷害。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.