Low-Level File IO
Opening files
open
#include <fcntl.h>
...
int open(const char *filename, int flags [, mode_t mode])
flags: O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC, zO_APPEND
- Opens or creates a raw data file.
- Returns -1 on error.
Reading files
read
#include <unistd.h>
...
ssize_t read(int filedes, void *buffer, size_t size)
- Reads from a raw data file.
- Does not automatically add an
end-of-string character.
- Returns the number of bytes read.
- Returns 0 on end-of-file, and -1 on
error.
pread
ssize_t pread (int filedes, void *buffer, size_t size, off_t offset)
Writing files
write
#include <unistd.h>
...
ssize_t write(int filedes, const void *buffer, size_t size)
- Writes to a raw data file.
- Returns the number of bytes written.
- Returns -1 on error.
pwrite
ssize_t pwrite (int filedes, const void *buffer, size_t size, off_t offset)
Seeking
lseek
#include <unistd.h>
...
off_t lseek (int filedes, off_t offset, int whence)
whence (offset is relative to)
SEEK_SET: Beginning of the file.
SEEK_CUR: Current file position.
SEEK_END: End of the file.
- Sets the file position.
- Returns the resulting file
position.
Closing files
close
#include <unistd.h>
...
int close (int filedes)
- Closes a raw data file.
...
int open(const char *filename, int flags [, mode_t mode])
flags: O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC, zO_APPEND
#include <unistd.h>
...
ssize_t read(int filedes, void *buffer, size_t size)
- Reads from a raw data file.
- Does not automatically add an end-of-string character.
- Returns the number of bytes read.
- Returns 0 on end-of-file, and -1 on error.
ssize_t pread (int filedes, void *buffer, size_t size, off_t offset)
Writing files
write
#include <unistd.h>
...
ssize_t write(int filedes, const void *buffer, size_t size)
- Writes to a raw data file.
- Returns the number of bytes written.
- Returns -1 on error.
pwrite
ssize_t pwrite (int filedes, const void *buffer, size_t size, off_t offset)
Seeking
lseek
#include <unistd.h>
...
off_t lseek (int filedes, off_t offset, int whence)
whence (offset is relative to)
SEEK_SET: Beginning of the file.
SEEK_CUR: Current file position.
SEEK_END: End of the file.
- Sets the file position.
- Returns the resulting file
position.
Closing files
close
#include <unistd.h>
...
int close (int filedes)
- Closes a raw data file.
...
ssize_t write(int filedes, const void *buffer, size_t size)
#include <unistd.h>
...
off_t lseek (int filedes, off_t offset, int whence)
whence (offset is relative to)
SEEK_SET: Beginning of the file.
SEEK_CUR: Current file position.
SEEK_END: End of the file.
- Sets the file position.
- Returns the resulting file position.
Closing files
close
#include <unistd.h>
...
int close (int filedes)
- Closes a raw data file.
...
int close (int filedes)