1、Write(写)系统调用向打开的文件写数据,顾名思义往文件写东西,这里也是需要缓冲区,获取你要写的东西到缓冲区,再从缓冲区写入到文件当中;这里write往文件写数据是通过二进制的形式写的;
(1)、write()格式:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
各参数及返回值的含义如下:
fd:要写入的文件的描述符。
buf:要写入的数据所存放的缓冲区。
count:要写入的字节数。
返回值:若成功返回已写的字节数,出错则返回-1并设置变量errno的值
(2)、使用write()时,可能遇到哪些情况?
返回值等于count
返回一个大于0小于count的值
阻塞
返回-1且errno的值为EINTR
返回-1且errno的值为EAGAIN
返回-1且errno的值为EBADF
返回-1且errno的值为EFAULT
返回-1且errno的值为EPIPE
返回的count是实际写入文件的字节数,其他的errno这些参数可以找man write(linux man手册),来看是什么错误,这里就不说了;
(3)、例子:
//这些头文件可以直接通过man来找;
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define SIZE 1024
int main()
{
int fd = open("abc", O_WRONLY|O_CREAT, 0777);
if (fd == -1)
{
perror ("open");
return -1;
}
char buf[SIZE] = {0};
while (1)
{
fgets (buf, SIZE, stdin); //死循环中,fgets()此刻处于等待状态;需要你强制结束程序;
if (strncmp ("end", buf, 3) == 0)
break;
ssize_t ret = write(fd, buf, strlen(buf)); //再一次执行这个程序时候会有覆盖(他会继续从头开始写入文件)
if (ret == -1)
{
perror ("write");
}
printf ("要写的字节数 :%d, 实际写的字节数: %d\n", SIZE, ret);
}
close(fd);
return 0;
}
2、文件的复制:
(1)、思想:复制就是read()和write()的两个过程,把1文件的内容读到缓冲区,在把缓冲区的内容写到2文件中;
文件1——>先读到——>buf
Buf——–>再写到——->文件2
(2)、例子
//把文件1 当中的ppt复制到文件2中
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define SIZE 1024
int main()
{
//打开要读的文件
int fd1 = open("1.ppt", O_RDONLY);
if (fd1 == -1)
{
perror ("open fd1");
return -1;
}
//打开要写进去的文件;
int fd2 = open("2.ppt", O_RDONLY);
if (fd2 == -1)
{
perror ("open fd2");
return -1;
}
int ret = 0;
char buf[SIZE] = {0};
//读到缓冲区,在从缓冲区写到fd2;
while (ret = read(fd1,buf,SIZE))
{
if(ret == -1)
{
perror("read");
break;
}
write(fd2,buf,ret);//读到ret 个字节,所以不用担心会读到前一次buf中的内容
}
printf("文件复制完成\n");
close(fd1);
close(fd2);
return 0;
}