Opening a File for Appending Data 

To open a file so that you can append data to the end of it, use the FOR APPENDING addition in the OPEN DATASET statement:

Syntax

OPEN DATASET <dsn> FOR APPENDING.

This statement opens a file to which you can append data. If the file does not already exist, it is created automatically. If it does exist, but is closed, the system opens it, and sets the position to the end of the file. If the file exists and is already open (for read or write access, or for appending), the position is set to the end of the file. SY-SUBRC is always 0.

It is good programming style to close files that are already open before you reopen them for a different operation (for further information about closing files, refer to Closing a File).

DATA FNAME(60) VALUE 'myfile'.

DATA NUM TYPE I.

OPEN DATASET FNAME FOR OUTPUT.
DO 5 TIMES.
   NUM = NUM + 1.
   TRANSFER NUM TO FNAME.
ENDDO.

OPEN DATASET FNAME FOR INPUT.

OPEN DATASET FNAME FOR APPENDING.
NUM = 0.
DO 5 TIMES.
   NUM = NUM + 10.
   TRANSFER NUM TO FNAME.
ENDDO.

OPEN DATASET FNAME FOR INPUT.
DO.
  READ DATASET FNAME INTO NUM.
  IF SY-SUBRC <> 0.
    EXIT.
  ENDIF.
  WRITE / NUM.
ENDDO.

The output appears as follows:

1
2
3
4
5
10
20
30
40
50

This example opens the file "myfile" for write access and fills it with the five integers 1-5 (for further information about the TRANSFER statement, refer to Writing Data to Files). The next OPEN DATASET statement resets the position to the beginning of the file. Then, the file is opened for appending data (the position is set to the end of the file). Five integers between 10 and 50 are written into the file. Finally, the program reads the contents of the file, and displays them on the screen.