File I/O
- Read Chapter 4
- This chapter examines the low level I/O calls which are part of the API
- Other I/O is built on top of these calls.
- When dealing with a file, the user is given a file descriptor
- This is an integer
- It is an index into a table.
- File descriptors are unique to a process
- But a child process will inherit file descriptors from the parent process
- So normally 0 is stdin, 1 is stdout and 2 is stderr
- But if your parent process has closed these, or reassigned these, then that may not be the case.
- STDIN_FILENO is defined to be 0, STDOUT_FILENO 1, STDERR_FILENO 2.
- /usr/include/unistd.h
- Basic File I/O routines
- open
- man 2 open
- int open(const char *pathname, int flags);
- int open(const char *pathname, int flags, mode_t mode);
- The pathname is a c style string, null terminated.
- We will look at flags in a moment.
- We will look at mode in a moment.
- Return is a -1 on error
- Or the file descriptor on success.
- Errno is set on error.
- read
- man 2 read
- ssize_t read(int fd, void *buf, size_t count);
- Attempts to read count bytes from the file descriptor fd into the buffer buf
- This starts at the current offset into the file (as recorded by the file descriptor)
- The number of bytes read is returned
- If this is less than count, then it was able to read some, but not all of the data requested.
- 0 indicates the end of the file.
- Or a -1 on error
- write
- ssize_t write(int fd, const void *buf, size_t count);
- Attempt to write count bytes from buf to the file descriptor fd.
- A positive return means that many bytes were written.
- A negative return means that there was an error.
- close
- int close(int fd);
- Attempt to close the file descriptor.
- This frees the fd for future use (and they are recycled)
- Return values as before
- The man page warns that write errors may not be reported until a close, thus checking the error is very important in critical programs.
- He gives an illustrative example, so do I