write()--Write to Descriptor
Syntax
#include <unistd.h> ssize_t write (int file_descriptor, const void *buf, size_t nbyte);
Service Program Name: QP0LLIB1
Default Public Authority: *USE
Threadsafe: Conditional; see Usage Notes.
The write() function writes nbyte bytes from buf to the file or socket associated with file_descriptor. nbyte should not be greater than INT_MAX (defined in the <limits.h> header file). If nbyte is zero, write() simply returns a value of zero without attempting any other action.
If file_descriptor refers to a "regular file" (a stream file that can support positioning the file offset) or any other type of file on which the job can do an lseek() operation, write() begins writing at the file offset associated with file_descriptor, unless O_APPEND is set for the file (see below). A successful write() increments the file offset by the number of bytes written. If the incremented file offset is greater than the previous length of the file, the length of the file is set to the new file offset.
If O_APPEND (defined in the <fcntl.h> header file) is set for the file, write() sets the file offset to the end of the file before writing the output.
If there is not enough room to write the requested number of bytes (for example, because there is not enough room on the disk), the write() function writes as many bytes as the remaining space can hold.
If write() is successful and nbyte is greater than zero, the change and modification times for the file are updated.
If file_descriptor refers to a descriptor obtained using the open() function with O_TEXTDATA specified, the data is written to the file assuming it is in textual form. The maximum number of bytes on a single write that can be supported for text data is 2,147,483,408 (2GB - 240) bytes. The data is converted from the code page of the application, job, or system to the code page of the file as follows:
- When writing to a true stream file, any line-formatting characters (such as
carriage return, tab, and end-of-file) are just converted from one code page to
another.
- When writing to a record file that is being used as a stream file:
- End-of-line characters are removed.
- Records are padded with blanks (for a source physical file member) or nulls (for a data physical file member).
- Tab characters are replaced by the appropriate number of blanks to the next tab position.
There are some important considerations if O_CCSID was specified on the open().
- The write() will attempt to convert all of the data in the
user's buffer. Successfully converted data will be written. Unconverted data is
usually assumed to be a partial character. Partial characters will be buffered
internally and data from the next consecutive write will be appended to the
buffered data. If incorrect data is provided on a consecutive write, the write
may fail with the [ECONVERT] error.
If an lseek() is performed, the file is closed, or the current job is ended, the buffered data will be discarded. Discarded data will not be written to the file. See lseek()--Set File Read/Write Offset for more information.
- Because of the above consideration and because of the possible expansion or contraction of converted data, applications using the O_CCSID flag should avoid assumptions about data size and the current file offset. For example, the user may supply a buffer to 100 bytes, but after an application has written the buffer to a new file, the file size may be 50, 200, or something else, depending on the CCSIDs involved.
If O_TEXTDATA was not specified on the open(), the data is written to the file without conversion. The application is responsible for handling the data.
When file_descriptor refers to a socket, the write() function writes to the socket identified by the socket descriptor.
Note: When the write completes successfully, the S_ISUID (set-user-ID) and S_ISGID (set-group-ID) bits of the file mode will be cleared. If the write is unsuccessful, the bits are undefined.
Write requests to a pipe or FIFO are handled the same as a regular file, with the following exceptions:
- The S_ISUID and S_ISGID file mode bits will not be cleared.
- There is no file offset associated with a pipe or FIFO. Each write request
will append to the end of the pipe or FIFO.
- Write requests of [PIPE_BUF] bytes or less will not be interleaved with
data from other threads performing writes on the same pipe or FIFO. Writes of
greater than [PIPE_BUF] bytes may have data interleaved on arbitrary boundaries
with writes by other threads, whether or not the O_NONBLOCK flag of the file
status flags is set.
[PIPE_BUF] refers to the value returned by pathconf() or fpathconf() when configuration variable value _PC_PIPE_BUF is specified.
- If the O_NONBLOCK flag was not specified and the pipe or FIFO is full, the
write request will block the calling thread until the requested amount of data
in nbyte is written.
- If the O_NONBLOCK flag was specified, then the following pertain to various
write requests:
- The write() function will not block the calling
thread.
- A write request for [PIPE_BUF] or fewer bytes will have the following
effect:
If there is sufficient space available in the pipe or FIFO, write() will transfer all the data and return the number of bytes requested. If there is not sufficient space in the pipe or FIFO, write() will transfer no data, return -1, and set errno to [EAGAIN].
- A write request for more than [PIPE_BUF] bytes will cause one of the
following:
- When at least one byte can be written, write() will
transfer what it can and return the number of bytes written.
- When no data can be written, write() will transfer no data, return -1, and set errno to [EAGAIN].
- When at least one byte can be written, write() will
transfer what it can and return the number of bytes written.
- The write() function will not block the calling
thread.
Parameters
- file_descriptor
- (Input) The descriptor of the file to which the data is to be written.
- buf
- (Input) A pointer to a buffer containing the data to be written.
- nbyte
- (Input) The size in bytes of the data to be written.
Authorities
No authorization is required.
Return Value
value | write() was successful. The
value returned is the number of bytes actually written. This number is less
than or equal to nbyte. |
-1 | write() was not successful. The errno global variable is set to indicate the error. |
Error Conditions
If write() is not successful, errno usually indicates one of the following errors. Under some conditions, errno could indicate an error other than those listed here.
Error condition | Additional information |
---|---|
[EACCES] |
If you are accessing a remote file through the Network File System, update operations to file permissions at the server are not reflected at the client until updates to data that is stored locally by the Network File System take place. (Several options on the Add Mounted File System (ADDMFS) command determine the time between refresh operations of local data.) Access to a remote file may also fail due to different mappings of user IDs (UID) or group IDs (GID) on the local and remote systems. If writing to a socket, this error code indicates one of the following:
|
[EAGAIN] |
If file_descriptor refers to a pipe or FIFO that has its O_NONBLOCK flag set, this error occurs if the write() would have blocked the calling thread. |
[EBADF] | |
[EBADFID] | |
[EBUSY] | |
[EDAMAGE] | |
[EFAULT] | |
[EFBIG] |
The size of the object would exceed the system allowed maximum size or the process soft file size limit. The file is a regular file, nbyte is greater than 0, and the starting offset is greater than or equal to 2 GB minus 2 bytes. |
[EINTR] | |
[EINVAL] |
For example, the file system that the file resides in does not support large files, and the starting offset exceeds 2GB minus 2 bytes. |
[EIO] | |
[EJRNDAMAGE] | |
[EJRNENTTOOLONG] | |
[EJRNINACTIVE] | |
[EJRNRCVSPC] | |
[ENEWJRN] | |
[ENEWJRNRCV] | |
[ENOMEM] | |
[ENOSPC] | |
[ENOTAVAIL] | |
[ENOTSAFE] | |
[ENXIO] | |
[ERESTART] | |
[ETRUNC] | |
[ESTALE] |
If you are accessing a remote file through the Network File System, the file may have been deleted at the server. |
[EUNKNOWN] |
When the descriptor refers to a socket, errno could indicate one of the following errors:
Error condition | Additional information |
---|---|
[ECONNREFUSED] |
This error code can only be returned on sockets that use a connectionless transport service. |
[EDESTADDRREQ] |
A destination address has not been associated with the socket pointed to by the fildes parameter. This error code can only be returned on sockets that use a connectionless transport service. |
[EHOSTDOWN] |
This error code can only be returned on sockets that use a connectionless transport service. |
[EHOSTUNREACH] |
This error code can only be returned on sockets that use a connectionless transport service. |
[EINTR] | |
[EMSGSIZE] |
The data to be sent could not be sent atomically because the size specified by nbyte is too large. |
[ENETDOWN] |
This error code can only be returned on sockets that use a connectionless transport service. |
[ENETUNREACH] |
This error code can only be returned on sockets that use a connectionless transport service. |
[ENOBUFS] | |
[ENOTCONN] |
This error code is returned only on sockets that use a connection-oriented transport service. |
[EPIPE] | |
[EUNATCH] | |
[EWOULDBLOCK] |
If interaction with a file server is required to access the object, errno could indicate one of the following errors:
Error condition | Additional information |
---|---|
[EADDRNOTAVAIL] | |
[ECONNABORTED] | |
[ECONNREFUSED] | |
[ECONNRESET] | |
[EHOSTDOWN] | |
[EHOSTUNREACH] | |
[ENETDOWN] | |
[ENETRESET] | |
[ENETUNREACH] | |
[ESTALE] |
If you are accessing a remote file through the Network File System, the file may have been deleted at the server. |
[ETIMEDOUT] | |
[EUNATCH] |
Error Messages
The following messages may be sent from this function:
Message ID | Error Message Text |
---|---|
CPE3418 E | Possible APAR condition or hardware failure. |
CPF3CF2 E | Error(s) occurred during running of &1 API. |
CPF9872 E | Program or service program &1 in library &2 ended. Reason code &3. |
CPFA081 E | Unable to set return value or error code. |
CPFA0D4 E | File system error occurred. Error number &1. |
Usage Notes
- This function will fail with error code [ENOTSAFE] when all the following
conditions are true:
- Where multiple threads exist in the job.
- The object on which this function is operating resides in a file system
that is not threadsafe. Only the following file systems are threadsafe for this
function:
- "Root" (/)
- QOpenSys
- User-defined
- QNTC
- QSYS.LIB
- Independent ASP QSYS.LIB
- QOPT
- Network File System
- QFileSvr.400
- Where multiple threads exist in the job.
- QSYS.LIB and independent ASP QSYS.LIB File System Differences
This function will fail with error code [ENOTSAFE] if the object on which this function is operating is a save file and multiple threads exist in the job.
If the file specified is a save file, only complete records will be written into the save file. A write() request that does not provide enough data to completely fill a save file record will cause the partial record's data to be saved by the file system. The saved partial record will then be combined with additional data on subsequent write()'s until a complete record may be written into the save file. If the save file is closed prior to a saved partial record being written into the save file, then the saved partial record is discarded, and the data in that partial record will need to be written again by the application.
A successful write() updates the change, modification, and access times for a database member using the normal rules that apply to database files. At most, the access time is updated once per day.
You should be careful when writing end-of-file characters in the QSYS.LIB and independent ASP QSYS.LIB file systems. These file systems end-of-file characters are symbolic; that is, they are stored outside the file member. However, some situations can result in actual, nonsymbolic end-of-file characters being written to a member. These nonsymbolic end-of-file characters could cause some tools or utilities to fail. For example:
- If you previously wrote an end-of-file character as the last character of a
member, do not continue to write data after that end-of-file character.
Continuing to write data will cause a nonsymbolic end-of-file to be written. As
a result, a compile of the member could fail.
- If you previously wrote an end-of-file character as the last character of a
member, do not write other end-of-file characters preceding it in the file.
This will cause a nonsymbolic end-of-file to be written. As a result, a compile
of the member could fail.
- If you previously used the integrated file system interface to manipulate a member that contains an end-of-file character, avoid using other interfaces (such as the Source Entry Utility or database reads and writes) to manipulate the member. If you use other interfaces after using the integrated file system interface, the end-of-file information will be lost.
- If you previously wrote an end-of-file character as the last character of a
member, do not continue to write data after that end-of-file character.
Continuing to write data will cause a nonsymbolic end-of-file to be written. As
a result, a compile of the member could fail.
- QOPT File System Differences
The change and modification times of the file are updated when the file is closed.
When writing to files on volumes formatted in Universal Disk Format (UDF), byte locks on the range being written are ignored.
- Network File System Differences
Local access to remote files through the Network File System may produce unexpected results due to conditions at the server. Once a file is open, subsequent requests to perform operations on the file can fail because file attributes are checked at the server on each request. If permissions on the file are made more restrictive at the server or the file is unlinked or made unavailable by the server for another client, your operation on an open file descriptor will fail when the local Network File System receives these updates. The local Network File System also impacts operations that retrieve file attributes. Recent changes at the server may not be available at your client yet, and old values may be returned from operations (several options on the Add Mounted File System (ADDMFS) command determine the time between refresh operations of local data).
Reading and writing to files with the Network File System relies on byte-range locking to guarantee data integrity. To prevent data inconsistency, use the fcntl() API to get and release these locks.
- QFileSvr.400 File System Differences
When connecting to a system at release V5R4M5 and earlier, QFileSvr.400 does not support large files. Otherwise, the starting offset is limited by the file system being accessed on the server.
- QNTC File System Differences
QNTC ignores any resource limits set using the setrlimit()--Set resource limit API when performing write() operations.
- Sockets Usage Notes
- write() only works with sockets on which a
connect() has been issued, since it does not allow the caller to
specify a destination address.
- To broadcast on an AF_INET socket, the socket option
SO_BROADCAST must be set (with a setsockopt()).
- When using a connection-oriented transport service, all errors except
[EUNATCH] and [EUNKNOWN] are mapped to
[EPIPE] on an output operation when either of the following occurs:
- A connection that is in progress is unsuccessful.
- An established connection is broken.
To get the actual error, use getsockopt() with the SO_ERROR option, or perform an input operation (for example, read()).
- write() only works with sockets on which a
connect() has been issued, since it does not allow the caller to
specify a destination address.
- For the file systems that do not support large files,
write() will return [EINVAL] if the starting offset exceeds 2GB minus
2 bytes, regardless of how the file was opened. For the file systems that do
support large files, write() will return [EFBIG] if the
starting offset exceeds 2GB minus 2 bytes and the file was not opened for large
file access.
- Using this function successfully on the /dev/null or /dev/zero character
special file results in a return value of the total number of bytes requested
to be written. No data is written to the character special file. In addition,
the change and modification times for the file are updated.
- If the write exceeds the process soft file size limit, signal SIFXFSZ is issued.
Related Information
- The <fcntl.h> file (see Header Files for UNIX®-Type Functions)
- The <unistd.h> file (see Header Files for UNIX-Type Functions)
- creat()--Create or Rewrite File
- dup()--Duplicate Open File Descriptor
- dup2()--Duplicate Open File Descriptor to Another Descriptor
- fclear()--Write (Binary Zeros) to Descriptor
- fclear64()--Write (Binary Zeros) to Descriptor (Large File Enabled)
- fcntl()--Perform File Control Command
- fpathconf()--Get Configurable Path Name Variables by Descriptor
- ioctl()--Perform I/O Control Request
- lseek()--Set File Read/Write Offset
- open()--Open File
- pathconf()--Get Configurable Path Name Variables
- pread()--Read from Descriptor with Offset
- pread64()--Read from Descriptor with Offset (large file enabled)
- pwrite()--Write to Descriptor with Offset
- pwrite64()--Write to Descriptor with Offset (large file enabled)
- read()--Read from Descriptor
- readv()--Read from Descriptor Using Multiple Buffers
- send()--Send Data
- sendmsg()--Send Data or Descriptors or Both
- sendto()--Send Data
- writev()--Write to Descriptor Using Multiple Buffers
Example
The following example writes a specific number of bytes to a file.
Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #define mega_string_len 1000000 main() { char *mega_string; int file_descriptor; int ret; char fn[]="write.file"; if ((mega_string = (char*) malloc(mega_string_len)) == NULL) perror("malloc() error"); else if ((file_descriptor = creat(fn, S_IWUSR)) < 0) perror("creat() error"); else { memset(mega_string, '0', mega_string_len); if ((ret = write(file_descriptor, mega_string, mega_string_len)) == -1) perror("write() error"); else printf("write() wrote %d bytes\n", ret); if (close(file_descriptor)!= 0) perror("close() error"); if (unlink(fn)!= 0) perror("unlink() error"); } free(mega_string); }
Output:
write() wrote 1000000 bytes
API introduced: V3R1