Reputation: 44439
In the following program I perform a basic interaction with an indexed file. When executed everything works as expected when I try to add a record, I even receive the success message. However when the code to read it - lees
- tries to find the corresponding ID, it can't find it. When I look at the size of the indexed file on my disk I can see it has a size of 0kb. What am I overlooking?
000100 IDENTIFICATION DIVISION.
000200 PROGRAM-ID. oef16_indexedfiles.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT indexfile ASSIGN TO "C:\Test\indexedfile.dat"
ORGANIZATION IS INDEXED
ACCESS IS DYNAMIC
RECORD KEY IS id-number
ALTERNATE KEY IS fname WITH DUPLICATES
ALTERNATE KEY IS lname WITH DUPLICATES
ALTERNATE KEY IS city WITH DUPLICATES
ALTERNATE KEY IS hobby WITH DUPLICATES.
DATA DIVISION.
FILE SECTION.
FD indexfile.
01 persoon.
02 id-number PIC 9.
02 name.
03 fname PIC A(25).
03 lname PIC A(30).
02 city PIC A(30).
02 hobby PIC X(40).
WORKING-STORAGE SECTION.
01 einde PIC X.
01 msg PIC X(50).
01 countno PIC 9 VALUE 1.
PROCEDURE DIVISION.
PGM.
PERFORM schrijf
PERFORM lees
STOP RUN.
check.
DISPLAY msg
ACCEPT einde
schrijf.
MOVE "1 = stoppen, 0 = doorgaan" TO msg
PERFORM check
OPEN I-O indexfile
PERFORM UNTIL einde = 1
MOVE countno TO id-number
DISPLAY "Enter your first name:"
ACCEPT fname
DISPLAY "Enter your last name:"
ACCEPT lname
DISPLAY "Enter your city:"
ACCEPT city
DISPLAY "Enter your hobby:"
ACCEPT hobby
WRITE persoon
INVALID KEY
DISPLAY "ERROR WRITING: " id-number
NOT INVALID KEY
DISPLAY "ID " id-number " by " fname " is added"
END-WRITE
ADD 1 TO countno
PERFORM check
END-PERFORM
CLOSE indexfile
MOVE 0 TO einde
lees.
OPEN INPUT indexfile
MOVE 1 TO id-number
READ indexfile
INVALID KEY
DISPLAY "Invalid key: " id-number
NOT INVALID KEY
DISPLAY id-number SPACE fname SPACE lname SPACE
city SPACE hobby
END-READ
CLOSE indexfile
MOVE 0 TO einde
ACCEPT einde
Upvotes: 1
Views: 844
Reputation: 44439
I've been pointed to the answer by someone else. In the write method (schrijf
) you have to use the OUTPUT
method instead of I-O
when opening a file.
For a detailed explanation: check out the comments below!
Upvotes: 0
Reputation: 4116
Try adding OPTIONAL to the SELECT phrase. Keep the OPEN I-O.
SELECT OPTIONAL indexfile ASSIGN TO "indexedfile.dat".
OPTIONAL will allow opening a non-existent file in preparation for first write.
Plus, follow Bill's advice; get used to checking FILE-STATUS after any OPEN (or any access for that matter).
After period terminating your paragraphs, and reformatting for FIXED form (a couple of display lines exceeded column 72), this code worked fine with OpenCOBOL once OPTIONAL was added. Before that it fails with
libcob: File does not exist (STATUS = 35) File : 'indexedfile.dat'
Upvotes: 4