Microsoft Small Basic

Program Listing: ZVF628
'-----------------------------------------------------------------------------
' Small Basic: Read and Write CSV Files
' http://social.technet.microsoft.com/wiki/contents/articles/20626.small-basic-read-and-write-csv-files.aspx
'-----------------------------------------------------------------------------

filename = "data.csv"
line_number = 1

'-----------------------------------------------------------------------------
' reads line for line, saves values to csv and shows them
'-----------------------------------------------------------------------------
' The following line could be harmful and has been automatically commented.
' line = File.ReadLine(filename, line_number)

While line <> ""
ExtractValues()

line_number = line_number + 1
' The following line could be harmful and has been automatically commented.
' line = File.ReadLine(filename, line_number)
EndWhile

ShowValues()



'-----------------------------------------------------------------------------
' ShowValues - writes all values of csv to the TextWindow
'-----------------------------------------------------------------------------
Sub ShowValues
For line_number = 1 to Array.GetItemCount(csv)
For value_number = 1 to Array.GetItemCount(csv[line_number])
TextWindow.Write(csv[line_number][value_number] + " ")
EndFor
TextWindow.WriteLine("")
EndFor
EndSub

'-----------------------------------------------------------------------------
' ExtractValues - saves all values of the current line to csv
'-----------------------------------------------------------------------------
Sub ExtractValues
'repeat as long as there is a comma
While Text.GetIndexOf(line,",") > 0
comma_position = Text.GetIndexOf(line, ",")

'save text until first comma
values[Array.GetItemCount(values)+1] = Text.GetSubText(line, 1, comma_position-1)

'remove saved text and comma from the line
line = Text.GetSubTextToEnd(line, comma_position+1)
EndWhile

'last value does not have a comma at the end
values[Array.GetItemCount(values)+1] = line

'append read values to csv
csv[Array.GetItemCount(csv)+1] = values

'reset variable
values = ""
EndSub