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:

  1. First, we use FILE-CONTROL to define the file we want to read from. We specify the file name accounts.dat and set the organization as LINE SEQUENTIAL, since the file contains records separated by new lines. Note, that similarly you can use the LINE SEQUENTIAL organization if you want to write each record on a new line.
  2. In the DATA DIVISION FILE SECTION, we define the file structure using FD InputFile InputRecord. We specify the fields Customer-Name and Account-Number.
  3. We define a working storage variable WS-EOF to check if we have reached the end of the file.
  4. Next, we move to the PROCEDURE DIVISION. We open the file using OPEN INPUT InputFile.
  5. We use a PERFORM UNTIL loop to read the file until we reach the end of the file. We read the file using READ InputFile INTO InputRecord.
  6. If we reach the end of the file (When AT END returns true), we set WS-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.

Why It's Important

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal