Reading From a Sequential File
Reading From a Sequential File
Welcome back! You've already learned how to create and write to a sequential file in COBOL. Now, it's time to take the next step: reading from a sequential file. This lesson is crucial because it allows you to retrieve and utilize stored data, which is a fundamental aspect of building dynamic applications, especially in sectors like finance, where data retrieval is frequent.
What You'll Learn
In this lesson, you will learn how to read records from an existing sequential file in COBOL. Understanding how to read files will help you build applications that can interact with stored data, enabling you to view, process, and analyze the information.
Let's consider this simple file with two customer details:
Here's a glimpse of the code you'll be working with:
The output of the code will be:
Let's analyze the code snippet:
- First, we use
FILE-CONTROLto define the file we want to read from. We specify the file nameaccounts.datand set the organization asLINE SEQUENTIAL, since the file contains records separated by new lines. Note, that similarly you can use theLINE SEQUENTIALorganization if you want to write each record on a new line. - In the
DATA DIVISIONFILE SECTION, we define the file structure usingFD InputFileInputRecord. We specify the fieldsCustomer-NameandAccount-Number. - We define a working storage variable
WS-EOFto check if we have reached the end of the file. - Next, we move to the
PROCEDURE DIVISION. We open the file usingOPEN INPUT InputFile. - We use a
PERFORM UNTILloop to read the file until we reach the end of the file. We read the file usingREAD InputFile INTO InputRecord. - If we reach the end of the file (When
AT ENDreturns true), we setWS-EOFto 'Y' and display a message. If we haven't reached the end of the file, we display the customer name and account number.
Finally, we close the file using CLOSE InputFile and stop the program using STOP RUN.
