Article
· May 11, 2016 1m read

The simplest snippet to read from file in InterSystems IRIS

Hi!

I believe the simplest is (to work with csv delimited by ";"):


set file = ##class(%File).%New( "data.csv" )
    set sc = file.Open( "R" ) 
    if $$$ISERR(sc) quit    ; or do smth

    while 'file.AtEnd {
        set str=file.ReadLine() 
        for i=1:1:$length( str, ";" ) {
            set id=$piece( str, ";" ,i ) 
            write !, id  // or do smth
        }
    }
    do file.Close()

Possible options:

different variants of error handling with sc code.

Embrace while loop into try/catch block.

And what's yours?

Discussion (16)2
Log in or sign up to continue

I would generally advise against using %File class for reading files as this is a very low level wrapper around the COS file commands. For example if you want to apply a translate table you need to know about the 'K' flag on the open command. I much prefer using the %Stream.FileBinary or %Stream.FileCharacter classes as these provide a much more consistent interface to the file.

Sorry, I am not criticizing what you have done.

I had to ask why you de-pieced the line based on ";"

and I was given an answer.

Suppose I did not ask, took your snippet and assumed to worked for all files?

All I am saying is the assumption you used (Russian style files) should be part of your documentation so someone not familiar with these style of files would know. Any (unfamiliar) assumptions should be documented.