Low level file input and output in C does not perform any formatting or buffering of data whatsoever, transferring blocks of anonymous data instead by making use of the underlying operating system's capabilities.
Low level I/O makes use of a file handle or descriptor, which is just a non-negative integer, to uniquely identify a file instead of using a pointer to the FILE structure as in the case of stream I/O.
As in the case of stream I/O a number of standard files are opened automatically :-
standard input --- 0
standard output --- 1
standard error --- 2
The following table lists some of the more common low level I/O functions, whose prototypes are given in and some associated constants are contained in and .
opens a disk file
closes a disk file
reads a buffer of data from disk
writes a buffer of data to disk
The open function has the following prototype and returns -1 if the open operation fails.
int open ( char *filename, int oflag [, int pmode] ) ;
where filename is the name of the file to be opened, oflag specifies the type of operations that are to be allowed on the file, and pmode specifies how a file is to be created if it does not exist.
oflag may be any logical combination of the following constants which are just bit flags combined using the bitwise OR operator.
appends to end of file
creates a new file if it doesn't exist
read only access
read write access
truncates file to zero length
write only access
pmode is only used when O_CREAT is specified as part of oflag and may be one of the following values
S_IREAD | S_IWRITE
This will actually set the read / write access permission of the file at the operating system level permanently unlike oflag which specifies read / write access just while your program uses the file.
The close() function has the following prototype
int close ( int handle ) ;
and closes the file associated with the specific handle.
The read() and write() functions have the following prototypes
int read( int handle, void *buffer, unsigned int count ) ;
int write( int handle, void *buffer, unsigned int count ) ;
where handle refers to a specific file opened with open(), buffer is the storage location for the data ( of any type ) and count is the maximum number of bytes to be read in the case of read() or the maximum number of bytes written in the case of write(). The function returns the number of bytes actually read or written or -1 if an error occurred during the operation.
Example : Program to read the first 1000 characters from a file and copy them to another.