2016-09-28 41 views
1

我一直在編寫一個程序,它使用OPEN語句從文件中讀取一個整數值,並在控制檯上輸出值。我遇到了分段錯誤Fortran從外部源讀取數據文件

在編譯期間,它似乎沒問題,沒有問題,但是當我運行該程序時,遇到了分段錯誤。

我已閱讀代碼,至今我沒有違反任何規則。有人能給我一個關於這個問題的想法嗎?

錯誤:

代碼:

program project5_03 
implicit none 
integer :: n = 0 
open (unit = 21, file = 'trial.txt', status = 'old') 
read (21,*) n 
print '(1x,a,i4)', "this is the value of n", n 
stop 
end program 

txt文件的內容僅僅是在第一行的數字 「1234」。

+2

顯示如何編譯代碼非常重要。回溯非常可疑,使用'-g -fbacktrace'或類似命令會更有用。 –

+0

你能成功編譯並運行更簡單的代碼嗎? – agentp

+0

請在'open'語句中使用'newunit'說明符。硬編碼文件識別單元非常容易出錯。 – jlokimlin

回答

0

嗯,代碼應該工作。如果你真的給我們提供了編譯器版本和選項,那本來會很好。 我的意思是說,你沒有關閉你打開的文件,但是由於程序終止,它不應該是一個問題。

我會做的是使用錯誤狀態和-message變量,像這樣:

program project5_03 
    implicit none 
    integer :: n 
    integer :: ios 
    character(len=200) :: iomsg 
    open (unit=21, file='trial.txt', status='old', iostat=ios, iomsg=iomsg) 
    call check(ios, iomsg, "OPEN") 
    read (21,*, iostat=ios, iomsg=iomsg) n 
    call check(ios, iomsg, "READ n") 
    write(*,'(1x,a,i4)', iostat=ios, iomsg=iomsg), "this is the value of n", n 
    call check(ios, iomsg, "WRITE to STDOUT") 
    stop 
contains 
    subroutine check(ios, iomsg, op) 
     implicit none 
     integer, intent(in) :: ios 
     character(len=*), intent(in) :: iomsg, op 
     if (ios == 0) return 
     print*, "Encountered Error ", ios, " during ", op 
     print*, iomsg 
     stop 
    end subroutine check 
end program 

也許這將幫助您找到的bug。

還有一個事實,即您使用integer :: n = 0 - 這對主程序不應該有問題,但在子程序中這意味着SAVE屬性。

+0

非常感謝。我可以通過改變我的編譯器來解決這個問題,如Fortran專家在facebook中所建議的。 :)我必須從TDM gfortran更改爲基於Cygwin的fortran ....謝謝 – DarkChemist