Read a flat file and write last but one record

Support for OS/VS COBOL, VS COBOL II, COBOL for OS/390 & VM and Enterprise COBOL for z/OS

Read a flat file and write last but one record

Postby sivareddy123 » Wed Feb 04, 2015 6:39 pm

Read a flat file and write last but one (I have n records in a file i have to n-1th) record in another flat file.

Could you please provide me the logic in COBOL ?

Thanks in advance
Posts: 3
Joined: Wed Feb 04, 2015 6:23 pm
Has thanked: 0 time
Been thanked: 0 time

Re: Read a flat file and write last but one record

Postby BillyBoyo » Wed Feb 04, 2015 7:53 pm

You don't know you have the last record, therefore the last-but one either, until you reach end-of-file.

You have to store a record. When you read the next record, it means you have the current, and the one before.

That's not completely there, as you need the one before that. So, when you read a new record, you store the previously stored record in another place, and store the current record. When you get end-of-file, you write out the "previously stored record in another place".

You have to take care of a couple of situations: empty file; file containing only one record. For the first perhaps DISPLAY "Disaster! File is empty!". For the second DISPLAY "There is only one record on the file, so can't write the penultimate one, sorry".
Global moderator
Posts: 3804
Joined: Tue Jan 25, 2011 12:02 am
Has thanked: 22 times
Been thanked: 265 times

Re: Read a flat file and write last but one record

Postby pranav283 » Wed Mar 18, 2015 12:05 pm

Yes Sivareddy,

When a READ statement is executed, it points to the current record.
So, you have to make sure that you store/preserve the previous record as well, as your now previous record had been a then current record.

You have to define two working sturage structures WSI1 and WSI2 or a table structure as 'WSI occurs 2 times'.

When you read a file 'FILEA' having record structure FILEA-REC,
at 'NOT AT END' condition -
Move WSI(2) to WSI(1)
and then Move FILE-REC to WSI(2)

Now when the READ statement executes for the last time (pointing at last record), at 'AT END ' condition,
you have to MOVE WSI(1) to OUTPUT-FILE-REC.

This does the work.
Please let us know once done.

Posts: 47
Joined: Sat Aug 30, 2014 3:52 pm
Has thanked: 2 times
Been thanked: 0 time

Return to IBM Cobol


  • Related topics
    Last post