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; }