write()--Write to Descriptor


Syntax
#include <unistd.h>

ssize_t write
  (int file_descriptor, const void *buf, size_t nbyte);

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 data is converted from the code page of the application, job, or system to the code page of the file as follows:

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.

Start of changeNote: 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.End of change

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.

[EACCES]
Permission denied.

An attempt was made to access an object in a way forbidden by its object access permissions.

The thread does not have access to the specified file, directory, component, or path.

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]
Operation would have caused the process to be suspended.

[EBADF]
Descriptor not valid.

A file descriptor argument was out of range, referred to a file that was not open, or a read or write request was made to a file that is not open for that operation.

A given file descriptor or directory pointer is not valid for this operation. The specified descriptor is incorrect, or does not refer to an open file. Or this write() request was made to a file that was only open for reading.

[EBADFID]
A file ID could not be assigned when linking an object to a directory.

The file ID table is missing or damaged.

To recover from this error, run the Reclaim Storage (RCLSTG) command as soon as possible.

[EBUSY]
Resource busy.

An attempt was made to use a system resource that is not available at this time.

[EDAMAGE]
A damaged object was encountered.

A referenced object is damaged. The object cannot be used.

[EFAULT]
The address used for an argument is not correct.

In attempting to use an argument in a call, the system detected an address that is not valid.

While attempting to access a parameter passed to this function, the system detected an address that is not valid.

[EFBIG]
Object is too large.

The size of the object would exceed the system allowed maximum size.

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.

[EINVAL]
The value specified for the argument is not correct.

A function was passed incorrect argument values, or an operation was attempted on an object and the operation specified is not supported for that type of object.

An argument value is not valid, out of range, or NULL.

The file system that the file resides in does not support large files, and the starting offset exceeds 2GB minus 2 bytes.

[EIO]
Input/output error.

A physical I/O error occurred.

A referenced object may be damaged.

[ENOMEM]
Storage allocation request failed.

A function needed to allocate storage, but no storage is available.

There is not enough memory to perform the requested function.

[ENOSPC]
No space available.

The requested operations required additional space on the device and there is no space left. This could also be caused by exceeding the user profile storage limit when creating or transferring ownership of an object.

Insufficient space remains to hold the intended file, directory, or link.

[ENOTSAFE]
Function is not allowed in a job that is running with multiple threads.

[ETRUNC]
Data was truncated on an input, output, or update operation.

[ESTALE]
File or object handle rejected by server.

If you are accessing a remote file through the Network File System, the file may have been deleted at the server.

[EUNKNOWN]
Unknown system state.

The operation failed because of an unknown system state. See any messages in the job log and correct any errors that are indicated, then retry the operation.

When the descriptor refers to a socket, errno could indicate one of the following errors:

[ECONNREFUSED]
The destination socket refused an attempted connect operation.

This error code can only be returned on sockets that use a connectionless transport service.

[EDESTADDRREQ]
Operation requires destination address.

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]
A remote host is not available.

This error code can only be returned on sockets that use a connectionless transport service.

[EHOSTUNREACH]
A route to the remote host is not available.

This error code can only be returned on sockets that use a connectionless transport service.

[EINTR]
Interrupted function call.
[EMSGSIZE]
Message size out of range.

The data to be sent could not be sent atomically because the size specified by nbyte is too large.

[ENETDOWN]
The network is not currently available.

This error code can only be returned on sockets that use a connectionless transport service.

[ENETUNREACH]
Cannot reach the destination network.

This error code can only be returned on sockets that use a connectionless transport service.

[ENOBUFS]
There is not enough buffer space for the requested operation.
[ENOTCONN]
Requested operation requires a connection.

This error code can only be returned on sockets that use a connection-oriented transport service.

[EPIPE]
Broken pipe.
[EUNATCH]
The protocol required to support the specified address family is not available at this time.
[EWOULDBLOCK]
Operation would have caused the thread to be suspended.

If interaction with a file server is required to access the object, errno could indicate one of the following errors:

[EADDRNOTAVAIL]
Address not available.
[ECONNABORTED]
Connection ended abnormally.
[ECONNREFUSED]
The destination socket refused an attempted connect operation.
[ECONNRESET]
A connection with a remote socket was reset by that socket.
[EHOSTDOWN]
A remote host is not available.
[EHOSTUNREACH]
A route to the remote host is not available.
[ENETDOWN]
The network is not currently available.
[ENETRESET]
A socket is connected to a host that is no longer available.
[ENETUNREACH]
Cannot reach the destination network.
[ESTALE]
File or object handle rejected by server.

If you are accessing a remote file through the Network File System, the file may have been deleted at the server.

[ETIMEDOUT]
A remote host did not respond within the timeout period.
[EUNATCH]
The protocol required to support the specified address family is not available at this time.

Error Messages

The following messages may be sent from this function:

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.

Usage Notes

  1. This function will fail with error code [ENOTSAFE] when all the following conditions are true:

  2. QSYS.LIB File System Differences

    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 file system. QSYS.LIB 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:

  3. QOPT File System Differences

    The change and modification times of the file are updated when the file is closed.

  4. 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.

  5. Start of changeQFileSvr.400 File System Differences

    The largest buffer size allowed is 16 megabytes. If a larger buffer is passed, the error EINVAL will be received.End of change

  6. Sockets Usage Notes

    1. write() only works with sockets on which a connect() has been issued, since it does not allow the caller to specify a destination address.

    2. To broadcast on an AF_INET socket, the socket option SO_BROADCAST must be set (with a setsockopt()).

    3. 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()).

  7. 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.

Related Information

Example

The following example writes a specific number of bytes to a file:


#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.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);
    close(file_descriptor);
    unlink(fn);
  }
}

Output:

write() wrote 1000000 bytes


Top | Integrated File System APIs | APIs by category


[Information Center Home Page | Feedback ] [Legal | AS/400 Glossary]