1、用read write拷贝一张图片,图片就是二进制的普通文件。
diff 1.png 2.png 比较
eog 1.png 打开图片。或者到图形化界面,双击图片
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//以读的方式打开图片文件
int fd = open("./2.jpg",O_RDONLY);
if(fd < 0)
{
printf("文件打开失败\n");
return -1;
}
printf("文件打开成功\n");
//再打开一个普通文件,以二进制的方式写入图片文件
int fd1 = open("./3.jpg",O_WRONLY | O_CREAT | O_TRUNC, 0777);
if(fd1 < 0)
{
printf("文件打开失败\n");
return -1;
}
printf("文件打开成功\n");
//将图片文件的内容通过二进制方式读出来
char buf[32]="";
ssize_t res;
while(1)
{
bzero(buf,sizeof(buf)); //清零,防止读取时出错
res = read(fd,buf,sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res)
{
printf("文件读取完毕\n");
break;
}
write(fd1,buf,res);
}
if(close(fd) < 0)
{
perror("close");
return -1;
}
printf("关闭成功\n");
if(close(fd1) < 0)
{
perror("close");
return -1;
}
printf("关闭成功\n");
return 0;
}