#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数:
- fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
- buf:需要读取数据存放的地方,数组的地址(传出参数)
- count:指定的数组的大小
返回值:
- 成功:
>0: 返回实际的读取到的字节数
=0:文件已经读取完了
- 失败:-1 ,并且设置errno
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数:
- fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
- buf:要往磁盘写入的数据,数组
- count:要写的数据的实际的大小
返回值:
成功:实际写入的字节数
失败:返回-1,并设置errno
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
int srcfd = open("english.txt", O_RDONLY);
if(srcfd == -1){
perror("open");
return -1;
}
int destfd = open("copy.txt", O_WRONLY | O_CREAT, 0664);
if(destfd == -1){
perror("open");
return -1;
}
char buf[1024] = {0};
int len = 0;
while((len = read(srcfd, buf, sizeof(buf))) > 0){
write(destfd, buf, len);
}
close(destfd);
close(srcfd);
return 0;
}
nowcoder@nowcoder:~/linux/lession10$ ls
copyfile.c english.txt
nowcoder@nowcoder:~/linux/lession10$ gcc copyfile.c -o copy
nowcoder@nowcoder:~/linux/lession10$ ./copy
nowcoder@nowcoder:~/linux/lession10$ ll
总用量 280
drwxrwxr-x 2 nowcoder nowcoder 4096 3-р с 4 17:30 ./
drwxrwxr-x 12 nowcoder nowcoder 4096 3-р с 4 16:42 ../
-rwxrwxr-x 1 nowcoder nowcoder 8528 3-р с 4 17:30 copy*
-rw-rw-r-- 1 nowcoder nowcoder 1659 3-р с 4 17:29 copyfile.c
-rw-rw-r-- 1 nowcoder nowcoder 129772 3-р с 4 17:30 copy.txt
-rw-rw-r-- 1 nowcoder nowcoder 129772 3-р с 4 16:43 english.txt