Opening a File for Write Access
To open a file for writing, use the FOR OUTPUT addition to the OPEN DATASET statement.
Syntax
OPEN DATASET <dsn> FOR OUTPUT.
If the file does not already exist, it is created automatically. If it does already exist, but is closed, its contents are overwritten. If the file exists and is already open (for read or write access, or for appending), the position is reset to the beginning of the file. If the system can open the file <dsn> successfully, SY-SUBRC is set to 0. If not, it is set to 8.
DATA: MESS(60),
FNAME(10) VALUE '/tmp'.
OPEN DATASET FNAME FOR OUTPUT MESSAGE MESS.
IF SY-SUBRC <> 0.
WRITE: 'SY-SUBRC:', SY-SUBRC,
/ 'System Message:', MESS.
ENDIF.
If the R/3 System is ruining under UNIX, the output looks like this:
The system cannot open the file, since the name you specified is that of a directory.
The following program shows how the system sets the position when you open a file for writing. However, it is better 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
DATA FNAME(60) VALUE 'myfile'.
DATA NUM TYPE I.
OPEN DATASET FNAME FOR OUTPUT.
DO 10 TIMES.
NUM = NUM + 1.
TRANSFER NUM TO FNAME.
ENDDO.
PERFORM INPUT.
OPEN DATASET FNAME FOR OUTPUT.
NUM = 0.
DO 5 TIMES.
NUM = NUM + 10.
TRANSFER NUM TO FNAME.
ENDDO.
PERFORM INPUT.
CLOSE DATASET FNAME.
OPEN DATASET FNAME FOR OUTPUT.
NUM = 0.
DO 5 TIMES.
NUM = NUM + 20.
TRANSFER NUM TO FNAME.
ENDDO.
PERFORM INPUT.
FORM INPUT.
SKIP.
OPEN DATASET FNAME FOR INPUT.
DO.
READ DATASET FNAME INTO NUM.
IF SY-SUBRC <> 0.
EXIT.
ENDIF.
WRITE / NUM.
ENDDO.
ENDFORM.
The output appears as follows:
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
6
7
8
9
10
20
40
60
80
100
This example performs the following steps using the file "myfile":