ReadTextFile - Shows how to read lines of text from a text file using FReadLine

// ReadTextFile(pathName, filePath, outputWaveName, maxNumberOfLines)
// Reads all of the lines of text from the file into a new text wave.
// Returns 0 if OK or a non-zero error code.
// Read the comments for details.
Function ReadTextFile(pathName, filePath, outputWaveName, maxNumberOfLines)
    String pathName             // Symbolic path name or "" if filePath is full path. Can also be "" if filePath is "" to get Open File dialog.
    String filePath                 // File name, partial path or full path or "" to get Open File dialog.
    String outputWaveName           // NOTE: Overwrites existing wave, if any!
    Variable maxNumberOfLines       // Maximum expected number of lines in file.
   
    Variable refNum
    Variable err = 0
   
    if (strlen(filePath) == 0)          // Want Open File dialog?
        Open/D/R/P=$pathName refNum as filePath
        if (strlen(S_fileName) == 0)
            return -1               // User canceled.
        endif
        filePath = S_fileName       // This is a full path.
    endif
   
    Open/R/P=$pathName refNum as filePath
    if (GetRTError(1))
        return -2                   // Error. Probably file does not exist.
    endif
   
    Make/O/T/N=(maxNumberOfLines) $outputWaveName
    if (GetRTError(1))
        Close refNum
        return -3                   // Error. Probably there is already a numeric wave with this name.
    endif
   
    Wave/T tw = $outputWaveName
   
    Variable row
    for(row=0; row<maxNumberOfLines+1; row+=1)
        String data
        FReadLine refNum, data      // Terminates on CR, LF or CRLF.
        if (strlen(data) == 0)
            break                   // All done.
        endif
       
        if (row == maxNumberOfLines)
            err = -4                    // Error. File had more rows than specified maximum.
            break
        endif
       
        tw[row] = data
    endfor
   
    Close refNum
   
    Redimension/N=(row) tw
   
    return err                      // 0=success
End

Forum

Support

Gallery

Igor Pro 9

Learn More

Igor XOP Toolkit

Learn More

Igor NIDAQ Tools MX

Learn More