Standard Input、Output、and Error
File I/O vs Standard I/O
int fileno(FILE *stream); //此函式會檢測參數的串流,若發生 error 回傳 -1,成功則回傳一個 file descriptor
Unbuffered I/O
File Descriptors
The open(2) Function
int open(const char *pathname, int flags, mode_t mode);
在 NFS 中當有兩個以上 process 同時 append data 可能會損壞檔案,因為 NFS 本身沒有支援 append 方式,必須靠 client kernel 模擬,而無法應付 race condition
The creat(2) Function
int creat(const char *pathname, mode_t mode);
The close(2) Function
int close(int fd);
The lseek(2) Function
off_t lseek(int fd, off_t offset, int whence);
The read(2) Function
ssize_t read(int fd, void *buf, size_t count);
The write(2) Function
ssize_t write(int fd, const void *buf, size_t count);
I/O Efficiency
File Sharing
Atomic Operation
pread(2) And pwrite(2)
ssize_t pread(int fd, void *buf, size_t count, off_t offset); ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
dup(2) And dup2(2)
int dup(int oldfd); int dup2(int oldfd, int newfd);
sync(2), fsync(2) And fdatasync(2)
void sync(void); int fsync(int fd); int fdatasync(int fd);
fnctl(2)
int fcntl(int fd, int cmd, ... /* arg */ );
|=
Enable flag&=
Disable flag#include "apue.h" #include <fcntl.h> void set_fl(int fd, int flags) /* flags are file status flags to turn on */ { int val; if ((val = fcntl(fd, F_GETFL, 0)) < 0) err_sys("fcntl F_GETFL error"); val |= flags; /* turn on flags */ if (fcntl(fd, F_SETFL, val) < 0) err_sys("fcntl F_SETFL error"); }
ioctl(2)
int ioctl(int d, int request, ...);
/dev/fd
Standard I/O
Buffering
Newly opened streams are normally fully buffered, with one exception: a stream connected to an interactive device such as a terminal is initially line buffered.
int fflush(FILE *stream);
Function for Setting Buffer (3)
void setbuf(FILE *stream, char *buf); int setvbuf(FILE *stream, char *buf, int mode, size_t size);
Function for Open and Close Files (3)
FILE *fopen(const char *path, const char *mode); FILE *fdopen(int fd, const char *mode); FILE *freopen(const char *path, const char *mode, FILE *stream); int fclose(FILE *fp);
Function for Read and Write By Character (3)
//read character int getc(FILE *stream); int getchar(void);
//Test EOF or Error int feof(FILE *stream); int ferror(FILE *stream);
//write character int putc(int c, FILE *stream); int putchar(int c);
Function for Read and Write By Line
//read line char *fgets(char *s, int size, FILE *stream); char *gets(char *s);
//write line int fputs(const char *s, FILE *stream); int puts(const char *s);
Binary I/O
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream ); size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
Positioning a Stream
int fseek(FILE *stream, long offset, int whence); long ftell(FILE *stream); void rewind(FILE *stream);
Temporary Files
char *tmpnam(char *str); FILE *tmpfile(void);