|
UNIX Input/Output
Universal File I/O |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
int open(char *pathname, int flags, mode_t mode);
pathname
|
The path to the file |
flags
|
A bit mask specifying how the file will be accessed |
mode
|
An optional (except when creating) access permission |
| Return | A file descriptor (or -1 if an error occurs) |
flags
O_RDONLY
|
Read only |
O_WRONLY
|
Write only |
O_RDWR
|
Read and write |
O_CREAT
|
Create the file if it doesn't exist |
O_APPEND
|
Writes are always appended to the end of the file |
errno
EACCES
|
The file permissions don't allow the mode specified by flags |
EISDIR
|
Attempted to open a directory for writing |
EMFILE
|
Too many open files (for the process) |
ENFILE
|
Too many open files (for the system) |
errno
EBADF
|
fd isn't a valid open file descriptor |
EIO
|
An I/O error occurred |
ssize_t read(int fd, void *buffer, size_t count)
fd
|
The file descriptor to read from |
buffer
|
The ultimate location of the bytes in memory |
count
|
The maximum number of bytes to copy |
| Return | The number of bytes copied; 0 on EOF; -1 on error |
count bytes longerrno
EBADF
|
fd is invalid or not open for reading |
EIO
|
I/O error |
EISDIR
|
fd refers to a directory |
errno
EBADF
|
fd is invalid or not open for reading |
EDQUOT
|
The user's disk quota has been exhausted |
EIO
|
I/O error |
ENOSPC
|
The device has no room for the data |
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include "error_handler.h"
#define LENGTH 5
int
main(int argc, char **argv)
{
char level;
char id[LENGTH];
int fd;
ssize_t n;
level = '0';
fd = open("courses.txt", O_RDONLY);
if (fd <0) handle_error();
while ((n = read(fd, id, LENGTH)) == LENGTH)
{
if(id[2] != level)
{
level = id[2];
write(STDOUT_FILENO, "\n", 1);
}
write(STDOUT_FILENO, id, LENGTH);
write(STDOUT_FILENO, "\n", 1);
}
close(fd);
}