#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFSIZE 10
void oops(char *s1, char *s2)
{
fprintf(stderr,"Error: %s ",s1);
perror(s2);
exit(1);
}
int main(int argc, char *argv[])
{
char Buf[BUFSIZE];
int Infd, Outfd,nChars;
if(3 != argc)
{
fprintf(stderr,"usage : %s source destination\n"
,*argv);
exit(1);
}
//参数1是要创建的文件
if(-1 == (Outfd = creat(argv[1],0744)))
oops("Create Fail",argv[1]);
//参数2是要读取的文件
if(-1 == (Infd = open(argv[2],O_RDONLY)))
oops("Open Fail",argv[2]);
//只要可以读取到数据
while((nChars = read(Infd,Buf,BUFSIZE)) > 0)
{
//判断是否写入的和读取的大小相同
if(write(Outfd,Buf,nChars) != nChars)
{
oops("Write Error",argv[1]);
}
}
if(-1 == nChars)
oops("Read Error From",argv[2]);
//关闭文件描述符
if(-1 == close(Infd)||-1 == close(Outfd))
oops("Error Closing File","");
return 0;
}
CP命令的实现
最新推荐文章于 2024-10-09 19:49:12 发布
本文介绍了一个简单的文件复制程序实现过程,使用C语言并通过标准输入输出完成文件从源位置到目标位置的复制。程序中涉及错误处理机制确保了操作的安全性和稳定性。
3635

被折叠的 条评论
为什么被折叠?



