您的位置:首页 > 运维架构

系统IO 编写copy程序 简析对文件的操作

2015-03-17 21:34 155 查看
#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

#include <errno.h>

int main(int argc, char **argv)

{

//判断参数个数是否正确

if(argc != 3)
{
printf("Usage: %s <src> <dst>\n", argv[0]);
exit(1);
}

// 利用open函数打开文件,并返回文件描述符
int fd1 = open(argv[1], O_RDONLY);
if(fd1 < 0)
{
printf("open(argv[1]) is failed!:%s \n", argv[1], strerror(errno));
exit(1);
}
int fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);
if(fd2 < 0)
{
printf("open(argv[2]) is failed!:%s \n", argv[2]);
exit(1);
}

int nread, nwrite;
char *buf = malloc(200);

//不断地读写argv[1]中的内容并写入argv【2】,当满足条件时分别执行相应操作
while(1)
{

while((nread = read(fd1, buf, 200)) == -1 && errno == EINTR)

if(nread == -1)
{
printf("read() hits a real error: %s\n", strerror(errno));
exit(1);

}

if(nread == 0)

break;

char *p = buf;

//读取文件时有数据返回则执行一下循环。

while(nread > 0)
{
nwrite = write(fd2, p, nread);
nread -= nwrite;
p += nwrite;
}

}

//关闭文件

close(fd1);

close(fd2);

exit(0);

}

关于这个小程序所用到的文件操作函数中的参数,可以再Ubuntu下使用命令查看。如 man 2 open
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐