MainframeMaster
MainframeMaster

COBOL Tutorial

Progress0 of 0 lessons

COBOL File Handling

File handling in COBOL encompasses the comprehensive set of practices and techniques used to manage file operations reliably and safely. It includes proper file lifecycle management, error handling, file status checking, data validation, and implementing robust error recovery mechanisms. Good file handling ensures data integrity, prevents data loss, handles errors gracefully, and provides reliable file operations in production mainframe environments. Understanding file handling is essential for developing robust, maintainable COBOL applications.

What is File Handling?

File handling goes beyond simply performing file operations—it includes:

  • File Lifecycle Management: Proper opening, using, and closing of files
  • Error Detection and Handling: Checking file status and responding to errors appropriately
  • Data Validation: Ensuring data integrity before and after file operations
  • Error Recovery: Implementing strategies to recover from errors when possible
  • Resource Management: Ensuring files are properly closed and resources released
  • Logging and Auditing: Recording file operations for troubleshooting and compliance
  • Best Practices: Following established patterns for reliable file operations

Effective file handling is the foundation of reliable COBOL applications that work with external data.

The File Handling Lifecycle

Every file operation in COBOL follows a standard lifecycle that must be managed properly:

1. File Definition

Files must be defined in the ENVIRONMENT DIVISION (FILE-CONTROL) and DATA DIVISION (FILE SECTION):

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CUSTOMER-FILE ASSIGN TO 'CUSTOMER.DAT' ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS CUSTOMER-FILE-STATUS. DATA DIVISION. FILE SECTION. FD CUSTOMER-FILE RECORD CONTAINS 80 CHARACTERS. 01 CUSTOMER-RECORD. 05 CUSTOMER-ID PIC 9(5). 05 CUSTOMER-NAME PIC X(30). 05 CUSTOMER-ADDRESS PIC X(35). 05 CUSTOMER-STATUS PIC X. 05 FILLER PIC X(9). WORKING-STORAGE SECTION. 01 CUSTOMER-FILE-STATUS PIC XX. 88 FILE-SUCCESS VALUE '00'. 88 END-OF-FILE VALUE '10'. 88 FILE-NOT-FOUND VALUE '35'. 88 PERMANENT-ERROR VALUE '30'.

2. File Opening

Files must be opened before any operations can be performed. Always check the file status after opening:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PROCEDURE DIVISION. MAIN-PROCESS. PERFORM OPEN-FILES IF FILE-OPEN-SUCCESS PERFORM PROCESS-FILES ELSE PERFORM HANDLE-OPEN-ERROR END-IF PERFORM CLOSE-FILES STOP RUN. OPEN-FILES. OPEN INPUT CUSTOMER-FILE IF NOT FILE-SUCCESS DISPLAY 'ERROR: Failed to open customer file' DISPLAY 'Status: ' CUSTOMER-FILE-STATUS MOVE 'N' TO FILE-OPEN-SUCCESS-FLAG ELSE DISPLAY 'Customer file opened successfully' MOVE 'Y' TO FILE-OPEN-SUCCESS-FLAG END-IF.

3. File Operations

Perform file operations (READ, WRITE, REWRITE, DELETE) with proper status checking:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
PROCESS-FILES. PERFORM UNTIL END-OF-FILE READ CUSTOMER-FILE AT END SET END-OF-FILE TO TRUE NOT AT END IF FILE-SUCCESS PERFORM PROCESS-CUSTOMER-RECORD ELSE PERFORM HANDLE-READ-ERROR SET END-OF-FILE TO TRUE END-IF END-READ END-PERFORM.

4. File Closing

Always close files, even in error conditions:

cobol
1
2
3
4
5
6
7
8
CLOSE-FILES. IF FILE-OPEN-SUCCESS-FLAG = 'Y' CLOSE CUSTOMER-FILE IF NOT FILE-SUCCESS DISPLAY 'WARNING: Error closing customer file' DISPLAY 'Status: ' CUSTOMER-FILE-STATUS END-IF END-IF.

File Status Checking

File status checking is the cornerstone of proper file handling. The FILE STATUS field contains a two-character code that indicates the result of each file operation.

Common File Status Codes

Common COBOL File Status Codes
Status CodeMeaningTypical Action
"00"Successful operationContinue processing
"10"End of file reachedStop reading, handle EOF
"23"Record not foundHandle missing record
"30"Permanent errorLog error, terminate or recover
"35"File not foundCreate file or handle missing file
"22"Duplicate key (indexed files)Handle duplicate
"46"Read errorRetry or handle error

Using Condition Names for Readability

Use 88-level condition names to make status checking more readable:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
WORKING-STORAGE SECTION. 01 CUSTOMER-FILE-STATUS PIC XX. 88 FILE-SUCCESS VALUE '00'. 88 END-OF-FILE VALUE '10'. 88 RECORD-NOT-FOUND VALUE '23'. 88 PERMANENT-ERROR VALUE '30'. 88 FILE-NOT-FOUND VALUE '35'. 88 DUPLICATE-KEY VALUE '22'. PROCEDURE DIVISION. READ CUSTOMER-FILE EVALUATE TRUE WHEN FILE-SUCCESS PERFORM PROCESS-RECORD WHEN END-OF-FILE PERFORM HANDLE-END-OF-FILE WHEN RECORD-NOT-FOUND PERFORM HANDLE-RECORD-NOT-FOUND WHEN PERMANENT-ERROR PERFORM HANDLE-PERMANENT-ERROR WHEN OTHER PERFORM HANDLE-UNKNOWN-ERROR END-EVALUATE.

Error Handling Strategies

Effective error handling is critical for robust file operations. Here are common strategies:

Strategy 1: Explicit Error Checking

Check file status after every operation and handle errors explicitly:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
READ-CUSTOMER-RECORD. READ CUSTOMER-FILE IF NOT FILE-SUCCESS EVALUATE CUSTOMER-FILE-STATUS WHEN '10' DISPLAY 'End of customer file reached' MOVE 'Y' TO EOF-FLAG WHEN '23' DISPLAY 'Customer record not found' ADD 1 TO NOT-FOUND-COUNT WHEN '30' DISPLAY 'Permanent error reading customer file' PERFORM LOG-ERROR MOVE 'Y' TO ERROR-FLAG WHEN OTHER DISPLAY 'Unexpected error: ' CUSTOMER-FILE-STATUS PERFORM LOG-ERROR MOVE 'Y' TO ERROR-FLAG END-EVALUATE END-IF.

Strategy 2: Centralized Error Handler

Create a centralized error handling routine:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
HANDLE-FILE-ERROR. EVALUATE CUSTOMER-FILE-STATUS WHEN '00' CONTINUE WHEN '10' MOVE 'End of file' TO ERROR-MESSAGE MOVE 'I' TO ERROR-SEVERITY WHEN '23' MOVE 'Record not found' TO ERROR-MESSAGE MOVE 'W' TO ERROR-SEVERITY WHEN '30' MOVE 'Permanent file error' TO ERROR-MESSAGE MOVE 'E' TO ERROR-SEVERITY WHEN '35' MOVE 'File not found' TO ERROR-MESSAGE MOVE 'E' TO ERROR-SEVERITY WHEN OTHER STRING 'Unknown file error: ' CUSTOMER-FILE-STATUS DELIMITED BY SIZE INTO ERROR-MESSAGE MOVE 'E' TO ERROR-SEVERITY END-EVALUATE PERFORM LOG-ERROR-TO-FILE IF ERROR-SEVERITY = 'E' MOVE 'Y' TO CRITICAL-ERROR-FLAG END-IF.

Strategy 3: Retry Logic for Transient Errors

Implement retry logic for errors that might be transient:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
READ-WITH-RETRY. MOVE 0 TO RETRY-COUNT PERFORM UNTIL FILE-SUCCESS OR RETRY-COUNT >= MAX-RETRIES READ CUSTOMER-FILE IF NOT FILE-SUCCESS ADD 1 TO RETRY-COUNT IF RETRY-COUNT < MAX-RETRIES DISPLAY 'Retry attempt: ' RETRY-COUNT PERFORM WAIT-BEFORE-RETRY ELSE PERFORM HANDLE-PERMANENT-ERROR END-IF END-IF END-PERFORM.

File Opening Modes

Understanding file opening modes is crucial for proper file handling:

COBOL File Opening Modes
Open ModeAllowed OperationsTypical Use
OPEN INPUTREAD onlyReading existing files
OPEN OUTPUTWRITE onlyCreating new files or overwriting existing
OPEN I-OREAD, REWRITE, DELETEUpdating existing files
OPEN EXTENDWRITE only (append)Adding records to existing files

Example: Proper Mode Selection

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
*> Reading from a file OPEN INPUT CUSTOMER-FILE IF FILE-SUCCESS PERFORM READ-CUSTOMER-RECORDS END-IF CLOSE CUSTOMER-FILE *> Creating a new file OPEN OUTPUT REPORT-FILE IF FILE-SUCCESS PERFORM WRITE-REPORT-HEADER PERFORM WRITE-REPORT-DETAILS END-IF CLOSE REPORT-FILE *> Updating existing records OPEN I-O CUSTOMER-FILE IF FILE-SUCCESS PERFORM UPDATE-CUSTOMER-RECORDS END-IF CLOSE CUSTOMER-FILE *> Appending to existing file OPEN EXTEND TRANSACTION-LOG IF FILE-SUCCESS PERFORM WRITE-TRANSACTION-RECORD END-IF CLOSE TRANSACTION-LOG

Best Practices for File Handling

Follow these best practices for reliable file handling:

  • Always Check File Status: Check FILE STATUS after every file operation (OPEN, READ, WRITE, REWRITE, DELETE, CLOSE). Never assume operations succeed.
  • Use Meaningful Condition Names: Define 88-level condition names for file status codes to make code self-documenting and easier to maintain.
  • Close Files in All Paths: Ensure files are closed in normal completion paths, error paths, and exit routines. Use cleanup routines if necessary.
  • Validate Before Operations: Validate data before writing to files. Check that required fields are present and in correct format.
  • Handle End-of-File Explicitly: Always handle end-of-file conditions explicitly using AT END clauses or status checking.
  • Use Appropriate Open Modes: Open files in the correct mode for the intended operations. Don't try to write to INPUT files or read from OUTPUT files.
  • Implement Error Logging: Log all file errors to error files or system logs for troubleshooting and auditing.
  • Test Error Conditions: Test your error handling by simulating error conditions (missing files, invalid data, etc.).
  • Document File Dependencies: Document which files your program requires, their expected formats, and any dependencies between files.
  • Use Consistent Patterns: Follow consistent file handling patterns throughout your program for maintainability.

Complete File Handling Example

Here's a complete example demonstrating proper file handling:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
IDENTIFICATION DIVISION. PROGRAM-ID. FILE-HANDLING-EXAMPLE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT INPUT-FILE ASSIGN TO 'INPUT.DAT' ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS INPUT-FILE-STATUS. SELECT OUTPUT-FILE ASSIGN TO 'OUTPUT.DAT' ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS OUTPUT-FILE-STATUS. SELECT ERROR-LOG-FILE ASSIGN TO 'ERRORS.LOG' ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS ERROR-LOG-STATUS. DATA DIVISION. FILE SECTION. FD INPUT-FILE RECORD CONTAINS 80 CHARACTERS. 01 INPUT-RECORD PIC X(80). FD OUTPUT-FILE RECORD CONTAINS 80 CHARACTERS. 01 OUTPUT-RECORD PIC X(80). FD ERROR-LOG-FILE RECORD CONTAINS 132 CHARACTERS. 01 ERROR-LOG-RECORD PIC X(132). WORKING-STORAGE SECTION. 01 FILE-STATUS-FIELDS. 05 INPUT-FILE-STATUS PIC XX. 88 INPUT-SUCCESS VALUE '00'. 88 INPUT-EOF VALUE '10'. 88 INPUT-ERROR VALUE '30', '35', '46'. 05 OUTPUT-FILE-STATUS PIC XX. 88 OUTPUT-SUCCESS VALUE '00'. 88 OUTPUT-ERROR VALUE '30', '35', '46'. 05 ERROR-LOG-STATUS PIC XX. 88 ERROR-LOG-SUCCESS VALUE '00'. 01 PROCESSING-FLAGS. 05 EOF-FLAG PIC X VALUE 'N'. 88 END-OF-FILE VALUE 'Y'. 05 ERROR-FLAG PIC X VALUE 'N'. 88 CRITICAL-ERROR VALUE 'Y'. 05 FILES-OPENED PIC X VALUE 'N'. 88 FILES-ARE-OPEN VALUE 'Y'. 01 COUNTERS. 05 RECORDS-READ PIC 9(7) VALUE ZERO. 05 RECORDS-WRITTEN PIC 9(7) VALUE ZERO. 05 ERROR-COUNT PIC 9(5) VALUE ZERO. 01 ERROR-MESSAGE PIC X(100). PROCEDURE DIVISION. MAIN-PROCESS. DISPLAY 'Starting file handling example...' PERFORM INITIALIZE-PROGRAM PERFORM OPEN-FILES IF FILES-ARE-OPEN AND NOT CRITICAL-ERROR PERFORM PROCESS-FILES END-IF PERFORM CLOSE-FILES PERFORM DISPLAY-STATISTICS STOP RUN. INITIALIZE-PROGRAM. MOVE ZERO TO RECORDS-READ MOVE ZERO TO RECORDS-WRITTEN MOVE ZERO TO ERROR-COUNT MOVE 'N' TO EOF-FLAG MOVE 'N' TO ERROR-FLAG MOVE 'N' TO FILES-OPENED. OPEN-FILES. DISPLAY 'Opening files...' OPEN INPUT INPUT-FILE IF NOT INPUT-SUCCESS PERFORM LOG-ERROR STRING 'Failed to open input file. Status: ' INPUT-FILE-STATUS DELIMITED BY SIZE INTO ERROR-MESSAGE DISPLAY ERROR-MESSAGE MOVE 'Y' TO ERROR-FLAG ELSE DISPLAY 'Input file opened successfully' OPEN OUTPUT OUTPUT-FILE IF NOT OUTPUT-SUCCESS PERFORM LOG-ERROR STRING 'Failed to open output file. Status: ' OUTPUT-FILE-STATUS DELIMITED BY SIZE INTO ERROR-MESSAGE DISPLAY ERROR-MESSAGE CLOSE INPUT-FILE MOVE 'Y' TO ERROR-FLAG ELSE DISPLAY 'Output file opened successfully' OPEN OUTPUT ERROR-LOG-FILE IF NOT ERROR-LOG-SUCCESS DISPLAY 'Warning: Could not open error log' ELSE DISPLAY 'Error log opened successfully' END-IF MOVE 'Y' TO FILES-OPENED END-IF END-IF. PROCESS-FILES. DISPLAY 'Processing files...' PERFORM UNTIL END-OF-FILE OR CRITICAL-ERROR READ INPUT-FILE AT END SET END-OF-FILE TO TRUE NOT AT END IF INPUT-SUCCESS ADD 1 TO RECORDS-READ PERFORM PROCESS-RECORD ELSE PERFORM HANDLE-READ-ERROR END-IF END-READ END-PERFORM. PROCESS-RECORD. *> Validate and process the record IF INPUT-RECORD NOT = SPACES MOVE INPUT-RECORD TO OUTPUT-RECORD WRITE OUTPUT-RECORD IF OUTPUT-SUCCESS ADD 1 TO RECORDS-WRITTEN ELSE PERFORM HANDLE-WRITE-ERROR END-IF END-IF. HANDLE-READ-ERROR. ADD 1 TO ERROR-COUNT STRING 'Error reading input file. Status: ' INPUT-FILE-STATUS DELIMITED BY SIZE INTO ERROR-MESSAGE DISPLAY ERROR-MESSAGE PERFORM LOG-ERROR IF INPUT-ERROR MOVE 'Y' TO ERROR-FLAG END-IF. HANDLE-WRITE-ERROR. ADD 1 TO ERROR-COUNT STRING 'Error writing output file. Status: ' OUTPUT-FILE-STATUS DELIMITED BY SIZE INTO ERROR-MESSAGE DISPLAY ERROR-MESSAGE PERFORM LOG-ERROR IF OUTPUT-ERROR MOVE 'Y' TO ERROR-FLAG END-IF. LOG-ERROR. IF ERROR-LOG-SUCCESS STRING FUNCTION CURRENT-DATE ' - ' ERROR-MESSAGE DELIMITED BY SIZE INTO ERROR-LOG-RECORD WRITE ERROR-LOG-RECORD END-IF. CLOSE-FILES. DISPLAY 'Closing files...' IF FILES-ARE-OPEN CLOSE INPUT-FILE IF NOT INPUT-SUCCESS DISPLAY 'Warning: Error closing input file' END-IF CLOSE OUTPUT-FILE IF NOT OUTPUT-SUCCESS DISPLAY 'Warning: Error closing output file' END-IF IF ERROR-LOG-SUCCESS CLOSE ERROR-LOG-FILE END-IF MOVE 'N' TO FILES-OPENED END-IF. DISPLAY-STATISTICS. DISPLAY 'Processing complete.' DISPLAY 'Records read: ' RECORDS-READ DISPLAY 'Records written: ' RECORDS-WRITTEN DISPLAY 'Errors encountered: ' ERROR-COUNT.

Common File Handling Mistakes

Avoid these common mistakes:

  • Not checking file status: Assuming operations always succeed leads to unreliable programs
  • Forgetting to close files: Files left open can cause resource leaks and data integrity issues
  • Wrong open mode: Opening files in the wrong mode for intended operations causes errors
  • Ignoring end-of-file: Not handling EOF can cause infinite loops or errors
  • No error recovery: Programs that don't handle errors gracefully fail in production
  • Inconsistent status checking: Checking status sometimes but not always creates unpredictable behavior

Explain Like I'm 5: File Handling

Think of file handling like taking care of a library book:

  • Opening a file is like checking out a book—you need to do it before you can read it
  • Reading from a file is like reading the book—you check each page to make sure it's there
  • Writing to a file is like writing in a notebook—you make sure the page is ready first
  • Checking file status is like checking if the book is in good condition—you want to know if something's wrong
  • Closing a file is like returning the book—you always return it, even if you didn't finish reading

Just like you'd check if a book page is torn before reading it, you check file status before using file data. And just like you always return books to the library, you always close files when you're done!

Practice Exercises

Complete these exercises to reinforce your understanding:

Exercise 1: Basic File Handling

Create a program that opens an input file, reads all records, validates each record, and writes valid records to an output file. Include proper error handling and file status checking.

Exercise 2: Error Logging

Enhance the program from Exercise 1 to log all errors (file errors and validation errors) to an error log file with timestamps.

Exercise 3: Retry Logic

Create a file reading routine that implements retry logic for transient errors, attempting up to 3 times before giving up.

Exercise 4: Multiple File Handling

Create a program that opens multiple files (input, output, error log), processes data from input to output, logs errors, and ensures all files are properly closed even if errors occur.

Exercise 5: Status Code Handler

Create a centralized file status handler that uses EVALUATE to handle all possible file status codes and provides appropriate error messages and recovery actions.

Test Your Knowledge

1. What should you do after every file operation in COBOL?

  • Nothing, file operations always succeed
  • Check the FILE STATUS field
  • Close the file immediately
  • Display a success message

2. What is the file status code for a successful operation?

  • "10"
  • "23"
  • "00"
  • "30"

3. When should you close a file in COBOL?

  • Only when processing completes successfully
  • Always, even in error conditions
  • Never, the system closes files automatically
  • Only when an error occurs

4. What is the purpose of using 88-level condition names for file status?

  • To improve performance
  • To make code more readable and maintainable
  • To reduce memory usage
  • To enable file compression

5. What happens if you try to write to a file opened for INPUT?

  • The write succeeds normally
  • A file status error occurs
  • The file is automatically converted to OUTPUT mode
  • Nothing, the operation is ignored

6. What is the recommended approach for handling multiple file operations?

  • Open all files at the start, process, close all at the end
  • Open and close files for each operation
  • Never close files, keep them open
  • Only open files when absolutely necessary

Related Concepts

Related Pages