1:查看man手册
man 2 read
man 2 write
注意:
- [ zero indicates end of file ]
- [ On error,-1 is returned,and errno is set appropriately ]
2:read/write函数
头文件#include<unistd.h>
ssize_t read(int fd,void *buf,size_t count)
fd
:文件描述符buf
:存数据的缓冲区count
:缓冲区大小返回值
- 成功:读到的字节数
- 失败:-1,设置errno
- 0:表示读到文件末尾
ssize_t write(int fd,const void *buf,size_t count)
fd
:文件描述符buf
:待写出数据的缓冲区count
:实际要写入的数据的大小返回值
- 成功:实际写入的字节数
- 失败:-1,设置errno
3:strace命令
shell 中使用strace命令跟踪程序执行,查看调用的系统函数。
4:实现简单cp功能
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
char buf[1024];
int n = 0;
int fd1 = open(argv[1],O_RDONLY);
int fd2 = open(argv[2],O_RDWR | O_CREAT | O_TRUNC,0664);
if( fd1 == -1){
perror("open argv1 error");
exit(1);
}
if(fd2 == -1){
perror("open argv2 error");
exit(1);
}
while( (n = read(fd1,buf,1024)) != 0){
if( n < 0){
perror("read error");
break;
}
write(fd2,buf,n);
}
close(fd1);
close(fd2);
}
5:缓冲区
read、write函数常常被称为Unbuffered I/O .指的是无用户及缓冲区。但不保证不使用内核缓冲区。
6:错误处理函数
printf("xxx error: %d\n",errno);
char *strerror(int errnum);
printf("xx error : %s\n",strerror(errno));
void perror(const char *s);
perror("open error");