CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.

The CSV format is flexible but somewhat ill-defined.

For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.



Task

Read a CSV file, change some values and save the changes back to a file.

For this task we will use the following CSV file:

C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20

Suggestions


 Show how to add a column, headed 'SUM', of the sums of the rows.
 If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.



*process source xref attributes or(!);
 csv: Proc Options(Main);
 /*********************************************************************
 * 19.10.2013 Walter Pachl
 * 'erase d:\csv.out'
 * 'set dd:in=d:\csv.in,recsize(300)'
 * 'set dd:out=d:\csv.out,recsize(300)'
 * Say 'Input:'
 * 'type csv.in'
 * 'csv'
 * Say ' '
 * Say 'Output:'
 * 'type csv.out'
 *********************************************************************/
 Dcl in  Record Input;
 Dcl out Record Output;
 On Endfile(in) Goto part2;
 Dcl (INDEX,LEFT,SUBSTR,TRIM) Builtin;
 
 Dcl (i,j,p,m,n) Bin Fixed(31) Init(0);
 Dcl s Char(100) Var;
 Dcl iline(10) Char(100) Var;
 Dcl a(20,20) Char(10) Var;
 Dcl sum Dec Fixed(3);
 Dcl oline Char(100) Var;
 
 Do i=1 By 1;
   Read File(in) Into(s);
   iline(i)=s;
   m=i;
   Call sep((s));
   End;
 
 part2:
 Do i=1 To m;
   If i=1 Then
     oline=iline(1)!!','!!'SUM';
   Else Do;
     sum=0;
     Do j=1 To n;
       sum=sum+a(i,j);
       End;
     oline=iline(i)!!','!!trim(sum);
     End;
   Write File(out) From(oline);
   End;
 
 sep: Procedure(line);
 Dcl line Char(*) Var;
 loop:
 Do j=1 By 1;
   p=index(line,',');
   If p>0 Then Do;
     a(i,j)=left(line,p-1);
     line=substr(line,p+1);
     End;
   Else Do;
     a(i,j)=line;
     Leave loop;
     End;
   End;
 n=j;
 End;
 
 End;