Reading “dynamic” filenames in Cobol programs

Cobol is good at dealing with files, and processing records. Original Cobol programs didn’t always have the facility to obtain a user specified filename, and as such relied on hard-coded filenames. One way of bypassing this is to use dynamic filenames. Consider a file called student.dat  containing the following information:

Skywalker      6543287Ackbar         1189283Chewbacca      9882870Palpatine      0000001

Now imagine a program which could take any type of file formatted in the same manner, read it in, and print out the names in the data file. Here is the program:

identification division.
program-id. fileio.

environment division.
input-output section.
file-control.
select ifile assign to dynamic ws-fname.

data division.
file section.
fd ifile
    record contains 88 characters.
*> Specify the structure of the records in the file
*> In this case there are 4 records, each containing two 
*> elements.
01 student-info.
  05 student-name occurs 4 times.
    10 stdnt-name pic x(15).
    10 stdnt-idno pic x(7).

working-storage section.
*> Define the loop index
01 i        pic 9.
77 ws-fname pic x(30).

procedure division.
 
    display "Filename containing book information? ".
    accept ws-fname. 

*> Open the file, read in the data into the structure 
*> and close the file
    open input ifile.
    read ifile
    end-read.
    close ifile.

    move 1 to i. 
*> Loop four times
    perform print-out 
        until i is greater than 4.
    stop run.

print-out.
    display "Student name is " stdnt-name(i).
    add 1 to i.

The file descriptor ifile is associated with dynamic ws-fname in the statement:

select ifile assign to dynamic ws-fname.

In the working-storage division, the filename variable  ws-fname is declared – as an array of characters (x), 30 elements in length.

77 ws-fname pic x(30).

Later, in the procedure division, the program then reads the users input and stores it in the variable ws-fname. After this, the file descriptor ifile is used exclusively to deal with the file.

accept ws-fname. 

If the file doesn’t exist (e.g. student1.dat), the program will throw an exception of the form:

libcob: File does not exist (STATUS = 35) File : 'student1.dat'

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s