Skip to main content
Engineering LibreTexts

12.4: File Read

  • Page ID
    54327
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    The file must be opened for “read” or “readwrite” access before any information can be read from the file. The general form of the write statement is as follows:

    read (unit=<unit number>, fmt=<format statement>,    &
                iostat=<variable>) <variables>
    

    The read is the same as the simple read; however, the unit number must be the number assigned during the open operation. If the status variable is set to less than 0, that is an indication that the end of the file has been reached. For example, if the file numbers.dat exists and has two numbers (on separate lines), the following declarations,

    integer :: num1, num2, myopenstatus, myreadstatus
    character(11) :: myfilename="numbers.txt"
    

    and the following Fortran statements,

    open (unit=12, file=myfilename, status="old",    &
                action="read", position="rewind",    &
                iostat=myopenstatus)
    if (myopenstatus > 0) stop "Cannot open file."
    
    read (12, '(i5)', iostat=myreadstatus) num1
    read (12, '(i5)', iostat=myreadstatus) num2
    

    would read information from the file.


    This page titled 12.4: File Read is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Ed Jorgensen via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

    • Was this article helpful?