Files: Application Server and Front End
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A business program often has to exchange a file with the outside world: read a bank statement that arrives as a text file,
write a list of expense claims for another system, or let a user pick a spreadsheet on their own computer. ABAP has two
completely separate ways to do this, because a file can live in two places. It can live on the application server, the
computer where the ABAP program runs, or on the front end (the SAP documentation also says presentation server), the
user’s own PC where SAP GUI runs. The first way is a set of statements, OPEN DATASET and its companions. The second is a
class, CL_GUI_FRONTEND_SERVICES, that asks SAP GUI to do the file work on the PC. After reading this page you can write
and read a text file on the application server, choose between text and binary mode and the right encoding, use a logical
file name so that no physical path is written in the program, protect a program against file names that come from outside,
move a file between the user’s PC and the system, and name the options that replace files in ABAP Cloud. The page is
written against Standard ABAP release 8.16 (ABAP Platform 2025 in SAP S/4HANA 2025 FPS02). Both ways are classic ABAP only:
the file statements and the front-end class are not part of ABAP for Cloud Development (release 9.20, 2608), whose keyword
documentation has no page for OPEN DATASET, and a cloud system has no SAP GUI on a user’s PC. Only the first listing could be
run here, in the open-source lab; the others need an SAP system and are labelled as not run here.
Before you read
-
Data Types and Data Objects: character-like and byte-like types, because text files take the first kind and binary files the second.
-
Internal Tables: a file is read into, or written from, an internal table line by line.
-
Exceptions: the file statements raise class-based exceptions that you can catch.
-
Authority Checks: opening a file performs an automatic authorization check.
-
ABAP Language Versions and Released APIs: why these statements are classic ABAP only.
Key terms
-
Application server: the computer that runs the ABAP program; the file statements work on its file system.
-
Presentation server (front end): the user’s PC on which SAP GUI runs; files there are reached through
CL_GUI_FRONTEND_SERVICES. -
File interface: the ABAP statements for files on the application server (
OPEN DATASET,READ DATASET,TRANSFER,CLOSE DATASET,DELETE DATASET). -
Physical file name: the real path and name of a file in the notation of the operating system.
-
Logical file name: a platform-independent name that customizing links to a physical path, so the program never contains the path.
-
Directory traversal: an attack in which a manipulated file name makes a program reach files outside the intended directory.
Two places for a file
The two worlds differ in who does the work and in what is available. The picture shows where the file lives and which ABAP tool reaches it.
| Application server | Front end | |
|---|---|---|
ABAP tool |
The statements of the file interface |
The class |
Runs where |
In the ABAP program, on the server |
In SAP GUI, on the user’s PC, started by the program |
Needs a user at a screen |
No: also works in a background job |
Yes: only programs run in dialog, from SAP GUI |
Typical use |
Interfaces, batch files, exports for other systems |
The user chooses a file to load or save |
Authorization |
Automatic check with |
The rights of the operating system user on the PC |
ABAP Cloud (9.20) |
Not available |
Not available |
The keyword documentation states the split directly: files on the application server are handled by the statements of the ABAP
file interface, and access to files on the presentation server is wrapped in the class CL_GUI_FRONTEND_SERVICES.
Files on the application server
The life of a file: open, transfer, close
A program never writes to a file directly. It first opens the file, which tells the operating system how the program wants to use it, then it moves data, then it closes the file. Five statements cover this life, and two more move or shorten the position inside a file.
| Statement | What it does |
|---|---|
|
Opens the file named in |
|
Passes data from the file to the data object, starting at the file pointer, and moves the pointer behind what was read. |
|
Writes the content of the data object to the file at the file pointer. |
|
Closes the file; data still buffered by the operating system is written first. A file that is not closed explicitly is closed when the program ends. |
|
Deletes the file; it may be open or closed. |
|
Read or change the file pointer and attributes of an open file. |
|
Sets the end of the file, which shortens it or extends it with hexadecimal zeros. |
The file pointer is the position in the file where the next read or write happens. It starts at the beginning, except in append mode, and it moves forward with every read and write.
Access type: what you may do with the file
The access addition after FOR is mandatory.
| Addition | Effect |
|---|---|
|
Opens for reading, pointer at the start. If the file does not exist, |
|
Opens for writing. An existing file is emptied, a missing file is created. Reading is also allowed. |
|
Opens for adding at the end, and creates the file if it is missing. |
|
Opens an existing file to change its content, pointer at the start. If the file does not exist, nothing is opened and |
FOR OUTPUT is the one that surprises newcomers: it destroys the old content at the moment of opening. A log file that must
grow uses FOR APPENDING.
Mode: text, binary and the legacy forms
The mode addition is also mandatory and decides what the bytes in the file mean.
-
IN BINARY MODE: the bytes of the data object are written unchanged, and read back unchanged. Use byte-like data objects (typexorxstring) for binary files. -
IN TEXT MODE ENCODING ...: the file holds characters. Only character-like data objects can be written and read. TheENCODINGaddition says how characters are stored:DEFAULT(the same asUTF-8),UTF-8withSKIPPING BYTE-ORDER MARKorWITH BYTE-ORDER MARK, orNON-UNICODE. On writing, trailing blanks of a fixed-length character field are cut off (not of astring) and an end-of-line marker is added; on reading, one call returns one line. -
IN LEGACY BINARY MODEandIN LEGACY TEXT MODE: for files in the format of a non-Unicode system, where the byte order or the code page must be named explicitly.
The Keyword Documentation gives a programming guideline: write text files in UTF-8 and with a byte order mark. The encoding page adds that a UTF-16 file can only be opened as a binary file.
The end-of-line marker needs one more decision. Without an addition it depends on the operating system of the application
server host, a profile parameter and the markers already used. The documentation therefore recommends the explicit addition
WITH NATIVE LINEFEED, WITH SMART LINEFEED, WITH UNIX LINEFEED or WITH WINDOWS LINEFEED after the encoding, and calls
the old TYPE addition for setting the marker obsolete.
The other additions
-
AT POSITION possets the file pointer in bytes when the file is opened (0 is the start, -1 the end). Free positions suit binary files better than text files, andSET DATASETis preferred over -1 for the end of the file. -
MESSAGE msgreceives the operating system’s message when opening fails. The documentation says it must always be used: without it the syntax check warns, and you cannot learn whysy-subrcis 8. -
IGNORING CONVERSION ERRORSsuppresses the exceptionCX_SY_CONVERSION_CODEPAGEand replaces a character that cannot be converted by#, or by the character named inREPLACEMENT CHARACTER. It is possible for text files, not for binary files. -
TYPE attrandFILTER opcomare operating-system-specific, and the filter starts an operating system command: avoid them unless an administrator asks for them.
A complete example: write, read, delete
The running example is the expense claim. The listing writes two claims as semicolon-separated lines to a text file, reads
them back line by line, deletes the file and shows what a read of the deleted file returns. It uses the lab’s reduced claim
fields (claim_id, status, amount); with the full ZEXP_CLAIM of
DDIC Tables and Structures the line would also carry the
currency and the employee. Every statement is followed by a sy-subrc check, which is the habit that the next section
explains.
REPORT zp_file.
TYPES: BEGIN OF ty_claim,
claim_id TYPE i,
status TYPE string,
amount TYPE i,
END OF ty_claim.
DATA claims TYPE STANDARD TABLE OF ty_claim WITH EMPTY KEY.
DATA claim TYPE ty_claim.
DATA line TYPE string.
DATA msg TYPE string.
DATA id TYPE string.
DATA st TYPE string.
DATA am TYPE string.
claims = VALUE #( ( claim_id = 1 status = `NEW` amount = 120 )
( claim_id = 2 status = `APPROVED` amount = 75 ) ).
CONSTANTS file TYPE string VALUE `claims.csv`.
OPEN DATASET file FOR OUTPUT IN TEXT MODE ENCODING UTF-8 MESSAGE msg.
IF sy-subrc <> 0.
WRITE: / `Cannot open for writing:`, msg.
RETURN.
ENDIF.
LOOP AT claims INTO claim.
line = |{ claim-claim_id };{ claim-status };{ claim-amount }|.
TRANSFER line TO file.
ENDLOOP.
CLOSE DATASET file.
OPEN DATASET file FOR INPUT IN TEXT MODE ENCODING UTF-8 MESSAGE msg.
IF sy-subrc <> 0.
WRITE: / `Cannot open for reading:`, msg.
RETURN.
ENDIF.
DO.
READ DATASET file INTO line.
IF sy-subrc <> 0.
EXIT.
ENDIF.
SPLIT line AT ';' INTO id st am.
WRITE: / |read: { id } { st } { am }|.
ENDDO.
CLOSE DATASET file.
DELETE DATASET file.
WRITE: / |delete sy-subrc = { sy-subrc }|.
OPEN DATASET file FOR INPUT IN TEXT MODE ENCODING UTF-8 MESSAGE msg.
WRITE: / |open after delete sy-subrc = { sy-subrc }|.
Run here, in a copy of the ABAP lab. The lab’s transpiler runtime has no file system of its own, so the lab’s
setup.mjs sets abap.context.dataset = new MemoryDataset() (the class MemoryDataset comes from
@abaplint/runtime), which keeps the "files" in memory. On a real application server the same statements use the file system
of the host. The output was:
read: 1 NEW 120
read: 2 APPROVED 75
delete sy-subrc = 0
open after delete sy-subrc = 8
The loop DO ... READ DATASET ... EXIT is the standard way to read a file: sy-subrc becomes 4 when the end of the file is
reached. A second run of the same kind, with two FOR APPENDING opens of one file, printed first, second and then
sy-subrc = 4 at the end of the file, which shows that appending keeps the old line.
Source: the statements follow Keyword Documentation for Standard ABAP: OPEN DATASET, READ DATASET and DELETE DATASET
Return codes and exceptions
The file statements report problems in two ways, the return code sy-subrc and class-based exceptions.
| Statement | sy-subrc |
OPEN DATASET |
|---|---|---|
0 the file was opened; 8 the operating system could not open it (read the |
|
0 data read; 4 an attempt to read after the end of the file. In a binary file 4 also means that data was read to the end and the target was longer than needed. |
|
Always 0, whether or not an exception was raised: never test it. |
|
Always 0 for a file opened without |
|
0 deleted; 4 could not be deleted. |
The catchable exceptions named on the keyword pages include CX_SY_FILE_OPEN (the file is already open, or cannot be opened),
CX_SY_FILE_AUTHORITY (no authorization for the file), CX_SY_TOO_MANY_FILES (a program may keep at most 100 files open per
internal session, and the platform may allow fewer), CX_SY_FILE_CLOSE (the file could not be closed, for instance for lack
of space) and CX_SY_CODEPAGE_CONVERTER_INIT and CX_SY_CONVERSION_CODEPAGE (a code page problem). Without a CATCH, each
one ends the program with a runtime error, for example OPEN_DATASET_NO_AUTHORITY.
Binary files and structures
A flat structure can be written to a file, but the documentation warns against text mode for mixed structures. To save numeric
or mixed data it recommends assigning the structure to a byte-like typed field symbol with ASSIGN ... CASTING and
transferring that, in a binary file. Such a file depends on the byte order and the code page of the system, so it is only
recommended for short-term storage inside the same system. For data that another system must read, write text (CSV or
JSON, see Outbound HTTP, JSON and XML) in UTF-8.
Physical and logical file names
A physical file name is the real path in the notation of the operating system, for example a directory on a Linux host. A
file name without an absolute path refers to the directory set by the profile parameter DIR_HOME, and with several
application server instances each instance usually has its own file system, unless an administrator shares one. Two problems
follow. A program that contains /usr/sap/... works on one platform only, and a path written in the code is a security
risk. SAP solves both with logical file names.
A logical file name is a name such as ZEXP_CLAIMS_EXPORT (an invented name for this example) that customizing links to a
physical path for each operating system. Client-independent names are maintained with transaction FILE, client-dependent ones
with the customizing activity SF01. The program asks the function module FILE_GET_NAME for the physical name at runtime. Its
parameters include LOGICAL_FILENAME (in upper case), PARAMETER_1 to PARAMETER_3 for placeholders in the path and
INCLUDING_DIR (set it to abap_true to get an absolute path). The exception FILE_NOT_FOUND is raised when the logical
name is unknown, and also when a name of data format DIR (a directory) is requested without INCLUDING_DIR.
DATA log_name TYPE filename-fileintern VALUE 'ZEXP_CLAIMS_EXPORT'.
DATA phys_name TYPE string.
DATA line TYPE string VALUE `1;NEW;120`.
DATA msg TYPE string.
CALL FUNCTION 'FILE_GET_NAME'
EXPORTING
logical_filename = log_name
including_dir = abap_true
IMPORTING
file_name = phys_name
EXCEPTIONS
file_not_found = 2
OTHERS = 4.
IF sy-subrc <> 0.
MESSAGE 'Logical file name is not defined' TYPE 'E'.
ENDIF.
TRY.
OPEN DATASET phys_name FOR OUTPUT IN TEXT MODE ENCODING UTF-8
WITH SMART LINEFEED MESSAGE msg.
IF sy-subrc <> 0.
MESSAGE msg TYPE 'E'.
ENDIF.
TRANSFER line TO phys_name.
CLOSE DATASET phys_name.
CATCH cx_sy_file_authority cx_sy_file_open.
MESSAGE 'The file cannot be used' TYPE 'E'.
ENDTRY.
Requires an SAP system; not run here. The logical file name must first be defined in transaction FILE, and the user needs
the authorization described next. The call of FILE_GET_NAME follows the sample of the documentation page on validating
file names.
Authorizations and safe file names
When a file is opened or deleted, the system performs an automatic authorization check. According to the documentation it
uses the authorization object S_DATASET and, together with the table SPTH, the object S_PATH. A missing authorization
raises CX_SY_FILE_AUTHORITY. The automatic check is only a minimum, and self-programmed checks with AUTHORITY-CHECK may be
needed too (see Authority Checks). One rule of the documentation is easy
to miss: use absolute paths, because a relative path is not resolved before the check, so the literal text is compared
instead.
The larger risk is directory traversal. If a file name, or part of it, comes from a selection screen, an interface or a
request, a caller may enter something like ../../secret/file and make the program read or delete a file outside the
intended directory. The keyword documentation names OPEN DATASET and DELETE DATASET as the statements concerned and gives
three defences:
-
use logical file names only and build the physical name with
FILE_GET_NAMEjust before the statement; then validation is usually not necessary; -
if the user enters a physical name, check it with the function module
FILE_VALIDATE_NAME, which compares it with a logical file name or a valid directory defined in transaction FILE or SF01; -
never pass an unchecked name to
OPEN DATASETorDELETE DATASET.
The documentation also notes that the class CL_FS_PATH offers methods to analyze, transform or create file names and path
entries.
Files on the front end
The class CL_GUI_FRONTEND_SERVICES
The class CL_GUI_FRONTEND_SERVICES lets the program run operating system functions on the PC of the user. It isolates the
program from the operating system of the PC and from the GUI implementation. It supports SAP GUI for Windows, SAP GUI for the
Java Environment and SAP GUI for HTML, and does not support Web Dynpro. The methods that matter for files are these.
| Methods | Purpose |
|---|---|
|
Transfer data between an internal table on the server and a file on the PC. |
|
Examine and process files on the PC. |
|
Examine and process directories on the PC. |
|
Run an operating system program or open a document. |
Most methods of the class call CL_GUI_CFW=>FLUSH internally, the call that sends buffered instructions to the PC; where the
caller has to do it, the method documentation says so (see
Control Framework and GUI Controls for the automation
queue). Because the work happens in SAP GUI, such a program only makes sense in dialog processing. The keyword example guards
with the function module GUI_IS_AVAILABLE, because a program started in the background has no GUI and would end with a
runtime error.
The next listing follows the keyword documentation example, shortened: it writes an XML representation of the claims through
GUI_DOWNLOAD in binary mode, then reads the file back with GUI_UPLOAD. The path is the example’s Windows path and the
rc values of the directory methods are checked as there.
DATA gui TYPE c LENGTH 1.
CALL FUNCTION 'GUI_IS_AVAILABLE'
IMPORTING
return = gui.
IF gui IS INITIAL.
RETURN.
ENDIF.
FINAL(file) = `C:\temp\my_temp\claims.xml`.
TYPES data_line TYPE x LENGTH 255.
DATA data_tab TYPE STANDARD TABLE OF data_line WITH EMPTY KEY.
SELECT * FROM zexp_claim INTO TABLE @DATA(claims).
CALL TRANSFORMATION id SOURCE claims = claims
RESULT XML data_tab.
cl_gui_frontend_services=>gui_download(
EXPORTING
filename = file
filetype = 'BIN'
CHANGING
data_tab = data_tab
EXCEPTIONS
OTHERS = 4 ).
IF sy-subrc <> 0.
MESSAGE 'File could not be written' TYPE 'I' DISPLAY LIKE 'E'.
RETURN.
ENDIF.
CLEAR data_tab.
cl_gui_frontend_services=>gui_upload(
EXPORTING
filename = file
filetype = 'BIN'
CHANGING
data_tab = data_tab
EXCEPTIONS
OTHERS = 4 ).
IF sy-subrc <> 0.
MESSAGE 'File could not be read' TYPE 'I' DISPLAY LIKE 'E'.
ENDIF.
Requires an SAP system with SAP GUI and a PC directory that exists; not run here. The table name ZEXP_CLAIM is the running
example’s table, and the keyword page does not use it; the transformation call follows its pattern of writing the data to a
table of byte lines.
The older function modules
Before the class existed, programs used function modules for the same jobs. The keyword documentation says that the methods
of CL_GUI_FRONTEND_SERVICES replace older function modules, among them GUI_UPLOAD, GUI_DOWNLOAD, WS_UPLOAD and
WS_DOWNLOAD. A page of the SAP Support knowledge base that lists replacements for obsolete function modules maps UPLOAD
and WS_UPLOAD to GUI_UPLOAD, DOWNLOAD and WS_DOWNLOAD to GUI_DOWNLOAD, and WS_QUERY to the methods FILE_EXIST and
DIRECTORY_EXIST; in each case the target may be the method of the class or the function module of the same name. Code that
still calls UPLOAD, DOWNLOAD, WS_UPLOAD or WS_DOWNLOAD, which older articles and teaching material show, should be
moved to the class.
Source: Keyword Documentation for Standard ABAP: Files on the Presentation Server and SAP Support content: NEW FM in Place of Obsolete FM (a knowledge-base page, not product documentation)
Which one to use
| Situation | Use |
|---|---|
A batch job, an interface or an export that nobody watches |
Files on the application server, with a logical file name and a UTF-8 text file |
The user picks a local file to load or a place to save a result |
|
A file that arrives from another system |
Application server directory, read by a job; the other system writes there, or sends through RFC or HTTP (see RFC, BAPIs and IDocs) |
A program that will run in ABAP Cloud |
No file statements: see the next section |
Alternatives in ABAP Cloud
ABAP for Cloud Development has no application server file system and no SAP GUI, and its keyword documentation has no page for
OPEN DATASET; the same lookup succeeds for a statement such as SELECT. The work that files do in classic programs is done
differently:
-
A file that a user uploads or downloads in a Fiori app. A RAP business object keeps the file in a large object field. The database table gets fields for the content (
abap.rawstring(0)), the MIME type and the file name, and the CDS view entity marks the content field with the annotation@Semantics.largeObject, which names the MIME type and file name fields and can list the accepted MIME types. The SAPUI5 documentation describes how a Fiori elements list report or object page then enables upload, download and deletion of the file ("stream support"). See RAP Overview for the business object. -
A file that another system provides. The data is fetched or sent with an outbound call, see Outbound HTTP, JSON and XML, or arrives through an inbound OData service, instead of through a shared directory.
-
Data that must be exchanged in batches. A released API or a business event replaces the file hand-over, see RAP Business Events.
In a system that offers both worlds, such as S/4HANA on premise, new code that must stay clean-core ready should use these patterns, and code that only has to run in classic reports can keep the file interface.
Common mistakes
| Mistake | Effect and cure |
|---|---|
|
The old content is deleted at once. Use |
No |
|
Testing |
Both always return 0. Catch the exceptions instead. |
Opening the same file twice |
|
Leaving files open |
At most 100 per internal session; open files are only closed automatically when the program ends. |
Writing a numeric or mixed structure to a text file |
Not possible in text mode. Convert to text, or use a binary file for short-term use inside one system. |
No explicit encoding or line feed |
The result depends on the host and on a profile parameter. Write |
A file name from a screen or interface used directly |
Directory traversal. Use a logical file name or |
|
There is no GUI. Guard with |
New code with |
Obsolete. Use |
Summary
-
A file is on the application server or on the user’s PC; ABAP has a separate tool for each, and both are classic ABAP only.
-
The file interface is
OPEN DATASET(access, mode, encoding),READ DATASET,TRANSFER,CLOSE DATASETandDELETE DATASET. Always addMESSAGE, write text files in UTF-8 with an explicit line feed, and remember thatFOR OUTPUTempties the file. -
Prefer logical file names (transaction FILE, function module
FILE_GET_NAME) to physical paths, and validate any name that comes from outside withFILE_VALIDATE_NAMEto stop directory traversal. -
Files on the PC go through
CL_GUI_FRONTEND_SERVICES(GUI_UPLOAD,GUI_DOWNLOAD), only in dialog programs; the old function modules such asWS_UPLOADare obsolete. -
In ABAP Cloud use a RAP large object field, an HTTP call or a released API instead of files.
References
-
SAP Support content: NEW FM in Place of Obsolete FM (knowledge-base page)