Syntax
#include <io.h> int read(int handle, char *buffer, unsigned int count);Description
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 C Set ++, read began with an underscore (_read). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, The Developer's Toolkit will map _read to read for you.
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: compact break=fit.
Value
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, carriage return characters are deleted from the input stream without affecting the file pointer.
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 ****************************************************************************/ }
Related Information