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[])
{
int fd = open(argv[1],O_RDONLY);
int fd1 = open(argv[2],O_WRONLY);
if(fd < 0)
{
perror("open");
return -1;
}
if(fd1 < 0)
{
perror("open");
return -1;
}
ssize_t res;
char arr[128] = "";
while(1)
{
bzero(arr,sizeof(arr));
res = read(fd,arr,sizeof(arr));
if(0 == res)
{
printf("文件读取完毕\n");
break;
}
else if(res < 0)
{
perror("read");
break;
}
write(fd1,arr,res);
}
if(close(fd) < 0)
{
perror("close");
return -1;
}
if(close(fd1) < 0)
{
perror("close");
return -1;
}
return 0;
}
使用fread打印到终端
#include <stdio.h>
int main(int argc, const char *argv[])
{
if(argc < 2)
{
printf("未输入文件名,获取失败\n");
return -1;
}
FILE* fp = fopen(argv[1],"r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
char a;
while(fread(&a,1,sizeof(a),fp) == sizeof(a))
{
printf("%C",a);
}
return 0;
}