Please do not use this as a reference. These are just my personal notes.
fd = 0 - stdin
fd = 1 - stdout
fd = 2 - stderr
Flags are bitwise OR'd to combine, e.g.
#ifndef O_TRUNC
#define O_TRUNC 00001000 /* not fcntl */
#endif
#ifndef O_APPEND
#define O_APPEND 00002000
#endif
fd = open("filename.txt", O_RDWR| O_TRUNC | O_APPEND)
- open()
- close()
- read()
- write()
int open(const char *pathname, int flags, mode_t mode);
flags:
O_RDONLY - read only
O_WRONLY - write only
O_RDWR - read and write
optional:
O_APPEND - append to file
O_CREAT - create file
O_TRUNC - truncate to zero length if exists
Returns the numbers of bytes actually read.
int close(int fd);
close(fd)
Returns the numbers of bytes actually read.
ssize_t read(int fd, void *buf, size_t count);
read(fd, buffer, count)
ssize_t write(int fd, const void *buf, size_t count);
write(fd, buffer, count)
#include <fcntl.h>
#include <stdlib.h>
#define BSIZE 16384
void main()
{
int fin, fout;
char buf[BSIZE];
int count;
char inputfile[] = "inputfile";
char outputfile[] = "outputfile";
if ((fin = open(inputfile, O_RDONLY)) < 0) {
perror(inputfile);
exit(1);
}
if ((fout = open(outputfile, O_WRONLY | O_CREAT, 0644)) < 0) {
perror(outputfile);
exit(1);
}
while ((count = read(fin, buf, BSIZE)) > 0)
write(fout, buf, count);
close(fin);
close(fout);
}