檔案IO 通用的I/O模型
阿新 • • 發佈:2019-01-14
Unix系統設計的核心理念: 檔案
一、概述
所有執行I/O操作的系統呼叫都已檔案描述符,一個非負整數 (通常是小數),來指代開啟的檔案。
檔案描述符用來表示所有型別的已開啟檔案,包括 管道、FIFO、socket、終端裝置和普通檔案。
1.1(I/O操作的四個系統呼叫
- int open(const char *pathname, int flags, mode_t mode);
-
- pathname 要開啟的檔案
- flags 指定開啟方式 O_RDONLY, O_WRONLY, or O_RDWR
- mode 指定建立檔案的許可權 (mode & ~umask). 如果沒建立可忽略
-
ssize_t read(int fd, void *buf, size_t count);
- 呼叫fd 所指代的開啟檔案至多讀取count個位元組的資料,儲存到buffer
- read() 系統呼叫 返回值為實際寫入檔案的位元組數,有可能小於count
- 讀到末尾(EOF)時 返回0
-
ssize_t write(int fd, const void *buf, size_t count);
- 呼叫 從buffer 讀取count個位元組到fd開啟的檔案中。
- 返回為實際寫入到檔案的值。 有可能小於count。
- int close(int fd);
- 所有I/O操作完成後,呼叫close() 釋放 檔案描述符fd 以及有關的核心資源
案例1.copy
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #ifndef BUF_SIZE #define BUF_SIZE 1024 #endif int main(int argc,char* argv[]) { int inPutFd,outPutFd,openFlags; mode_t filePerms;//鏂囦歡鏉冮檺鍙婄被鍨? ssize_t numRead; //瀛楄妭鏁?鏈夌鍙鋒暣鍨? char buf[BUF_SIZE]; if(argc!=3||strcmp(argv[1],"--help")==0) { printf("input oldfile new file\n"); exit(0); } inPutFd = open(argv[1],O_RDONLY); if(inPutFd== -1) { perror("open file"); } openFlags = O_CREAT|O_WRONLY|O_TRUNC; filePerms = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH; outPutFd=open(argv[2],openFlags,filePerms); if(outPutFd==-1) { perror("open fail"); exit(1); } while((numRead=read(inPutFd,buf,BUF_SIZE))>0) { if(write(outPutFd,buf,BUF_SIZE)!=numRead) { printf("not all \n"); } if(numRead==-1) { perror("error read"); exit(-1); } } if(close(inPutFd)==-1) exit(-1); if(close(outPutFd)==-1) exit(-1); return 0; }