Page 1 of 1

Read a flat file and write last but one record

PostPosted: Wed Feb 04, 2015 6:39 pm
by sivareddy123
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

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

PostPosted: Wed Feb 04, 2015 7:53 pm
by BillyBoyo
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".

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

PostPosted: Wed Mar 18, 2015 12:05 pm
by pranav283
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.

Thanks