### read -- Read Into Buffer

Format

>     #include <io.h>
>     int read(int handle, char *buffer, unsigned int count);

Language Level: XPG4, Extension
read reads count bytes from the file associated with handle into buffer. The read operation begins at the current position of the file pointer associated with the given file. After the read operation, the file pointer points to the next unread character.

Note: In earlier releases of the C/C++ run-time library, read began with an underscore (_read). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, IBM C and C++ Compilers will map _read to read for you.

Return Value
read returns the number of bytes placed in buffer. This number can be less than count if there are fewer than count bytes left in the file or if the file was opened in text mode. (See the note below.) The return value 0 indicates an attempt to read at end-of-file. A return value -1 indicates an error. If -1 is returned, the current file position is undefined, and errno is set to one of the following values:

Value | Meaning
EBADF | The given handle is incorrect, or the file is not open for reading, or the file is locked.
EOS2ERR | The call to the operating system was not successful.

Note: If the file was opened in text mode, the return value might not correspond to the number of bytes actually read. When text mode is in effect, the pair of characters carriage return and line feed are replaced by a single newline character.

Example
This example opens the file sample.dat and attempts to read from it.

    #include <io.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <string.h>

    int main(void)
    {
       int fh;
       char buffer[20];

       memset(buffer, '\0', 20);
       printf("\nCreating sample.dat.\n");
       system("echo Sample Program > sample.dat");
       if (-1 == (fh = open("sample.dat", O_RDWR|O_APPEND))) {
          perror("Unable to open sample.dat.");
          return EXIT_FAILURE;
       }
       if (7 != read(fh, buffer, 7)) {
          perror("Unable to read from sample.dat.");
          close(fh);
          return EXIT_FAILURE;
       }
       printf("Successfully read in the following:\n%s\n ", buffer);
       close(fh);
       return 0;

       /**************************************************************
          The output should be:

          Creating sample.dat.
          Successfully read in the following:
          Sample
       **************************************************************/
    }

creat -- Create New File
fread -- Read items
open -- Open File
_sopen -- Open Shared File
write -- Writes from Buffer to File