Reading a .csv file

2 Mar

Any spreadsheet can be saved as a .csv file, making it very easy for COBOL to use a spreadsheet as input.  This is a very common task in my workplace.  Let’s say we have a comma separated file that looks like this:

Doe,John,111 Main Street,Anytown,PA,12345,
Smith,Mary,654 Center Street,Sometown,WY,65432
Brown,Suzy,428 Lincoln Street,Smalltown,OH,34287,
White,Donald,91 Third Street,Bigtown,OK,43876,

This simple program reads this comma delimited file as input, and outputs it in report format.

Our output file will look like this:

Doe      John        111 Main Street       Anytown    PA    12345
Smith    Mary        654 Center Street     Sometown   WY    65432
Brown    Suzy        428 Lincoln Street    Smalltown  OH    34287
White    Donald      91 Third Street       Bigtown    OK    43876

Now let’s analyze our program.   First, we start out by opening our input file as INPUT, and our OUTPUT file as OUTPUT.  Be careful using the OPEN OUTPUT statement, as execution of this statement will clear any data currently in the file.   In this case, we want to start with an empty output file.

We then proceed to the READ-ROUTINE.   Notice that we move spaces to the input record before the READ statement.   ALWAYS, ALWAYS, ALWAYS do this before reading a record from a flat file.   I can think of no exceptions to this rule.   This clears any data left in the record from the previous read.  After we read a record, we then move spaces to our SEPARATE-IT field in WORKING-STORAGE, just to clear the contents of these fields. Next, we unstring the input-record, delimited by “,” into our SEPARATE-IT individual fields.  Not so bad, huh?  We now have each element of the comma-delimited record separated into its own field.   We need to generate an output report containing the same data as our original spreadsheet.  We do this by first clearing our OUTPUT-RECORD by moving spaces to it, and then moving the fields one at a time to the output fields.  We continue this procedure with each record read until our READ hits an end of file condition, in which case we GO TO the END-ROUTINE where we will close our files, and stop the run.

In my next post, I’ll show you how to create a .csv file as output.

0 Replies to “Reading a .csv file

    • Which is why comma is not a good delimiter to use. The pipe character “|” or tilde “~” are much better as they are unlikely to appear in the data.

Leave a Reply

Your email address will not be published. Required fields are marked *