Once you open a file or have a file handle, you can read from and write to the file by using DosRead and DosWrite.

DosWrite copies bytes from a buffer you specify to a file, device, or pipe.

Calling DosWrite with a handle for a file, pipe, or device transfers the number of bytes specified from a buffer location to the object. The system returns, in a parameter, the number of bytes actually written (which in the case of a disk file might not be the same as the number requested because of insufficient disk space).

To write to a file, you must first open it for writing or for reading and writing.

The following code fragment shows how to open the file SAMPLE.TXT again and write 512 bytes to it:

    #define INCL_DOSFILEMGR   /* File System values */
    #include <os2.h>

    #define BUF_SIZE 512

    HFILE   hf;
    ULONG   ulAction;
    BYTE    abBuffer[BUF_SIZE];
    ULONG   cbWritten;
    APIRET  ulrc;

    ulrc = DosOpen("SAMPLE.TXT",
                   &hf,
                   &ulAction,
                   0,
                   FILE_NORMAL,
                   FILE_CREATE,
                   OPEN_ACCESS_WRITEONLY |
                   OPEN_SHARE_DENYWRITE,
                   (PEAOP2) NULL);

    if (!ulrc) {
        DosWrite(hf,
                 abBuffer,
                 sizeof(abBuffer),
                 &cbWritten);

        DosClose(hf);
    }

DosWrite writes the contents of the buffer to the file. If it fails to write 512 bytes (for example, if the disk is full), the function puts the number of bytes written in the cbWritten variable. The data is read and written exactly as given; the function does not format the data-that is, they do not convert binary data to decimal strings, or vice versa.

The Write-Through Flag
If an application requires data to be written in a specific order, setting the Write-Through flag to 1 guarantees that actual I/O for a synchronous write is completed before the DosWrite returns. If this flag has been set with DosOpen for buffered I/O, and multiple synchronous writes are performed, the system cannot guarantee the actual order in which the data is written. For details on changing the state of the Write-Through flag, see Determining and Setting the State of a File or Device Handle.


[Back] [Next]