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.
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-CONTROL
to define the file we want to read from. We specify the file nameaccounts.dat
and set the organization asLINE SEQUENTIAL
, since the file contains records separated by new lines. Note, that similarly you can use theLINE SEQUENTIAL
organization if you want to write each record on a new line. - In the
DATA DIVISION
FILE SECTION
, we define the file structure usingFD InputFile
InputRecord
. We specify the fieldsCustomer-Name
andAccount-Number
. - We define a working storage variable
WS-EOF
to 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 UNTIL
loop 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 END
returns true), we setWS-EOF
to '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
.
Being able to read from files is essential for any COBOL programmer. Whether you’re working in banking, retail, or any data-driven industry, you need to know how to access and read data from files. By mastering this skill, you will be able to:
- Retrieve and display stored data
- Process and analyze information read from files
- Perform operations like data validation, updates, and reporting
This ability to read data complements your existing skill in writing to a file, thereby making you proficient in handling both ends of the file management process.
Excited to get started? Let's jump into the practice section and get some hands-on experience with reading from a sequential file in COBOL
!
