文件IO中read的应用以及利用read和write重写复制、粘贴功能
#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[])
{
//r、r+、w、w+、a、a+
//r:O_RDONLY
//r+:O_RDWR
//W:O_WRONLY | O_TRUNC | O_CREAT
//W+:O_RDWR | O_TRUNC | O_CREAT
//a:O_APPEND | O_CREAT
//a+:O_RDONLY | O_APPEND | O_CREAT
/* int fd = open("./01_open.txt",O_RDWR | O_CREAT | O_TRUNC,0777);
if(fd < 0)
{
perror("open");
return -1;
}
printf("fd = %d\n",fd);
//write将数据写入到指定文件中
//size_t write(int fd,const void* buf,size_t count)
char str[20] = "hello";
size_t res = 0;
res = write(fd,str,sizeof(str));
printf("res = %ld\n",res);
*/
//从指定文件中读取数据
//size_t read(int fd,const void* buf,size_t count)
umask(0);//将umask清0
int fd = open("./01_open.txt",O_RDONLY,0777);
int fd1 = open("./001_open.txt",O_WRONLY | O_CREAT | O_TRUNC,0777);
if(fd < 0)
{
perror("open1");
return -1;
}
if(fd1 < 0)
{
perror("open2");
return -1;
}
printf("fd = %d\n",fd);
printf("fd1 = %d\n",fd1);
char str1[22]="";
size_t res = 0;
//复制、read函数应用
while(1)
{
bzero(str1,sizeof(str1));
res = read(fd,str1,sizeof(str1)-1);
if(0 == res)
{
printf("读取完毕\n");
break;
}
else if(res < 0)
{
perror("read");
break;
}
printf("res = %ld str1 = %s\n",res,str1);
// write(1,str1,res);
}
//粘贴
res = write(fd1,str1,sizeof(str1));
printf("res = %ld\n",res);
if(close(fd)<0)
{
perror("close");
return -1;
}
return 0;
}