将一个文件读到另一个文件

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<errno.h>

#define BUFFER_SIZE 1024

int main(int argc, char **argv)
{
int from_fd, to_fd;
int read_bytes, write_bytes;
char buffer[BUFFER_SIZE];
char *ptr;

if(argc != 3)
{
fprintf(stderr,"Usage:%s fromfile tofile/n/a",argv[0]);
exit(1);
}

if((from_fd = open(argv[1],O_RDONLY)) == -1)
{
fprintf(stderr,"Open %s Error: %s/n",argv[1],strerror(errno));
exit(1);
}

if((to_fd = open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR)) == -1) //注意权限的设置
{
fprintf(stderr,"Open %s Error: %s/n",argv[2],strerror(errno));
exit(1);
}

while(read_bytes = read(from_fd,buffer,BUFFER_SIZE))
{
if((read_bytes == -1) && (errno != EINTR) )
break;
else if(read_bytes > 0)
{
ptr=buffer;
while(write_bytes = write(to_fd,ptr,read_bytes))
{
if((write_bytes == -1) && (errno != EINTR))
break;
else if(write_bytes == read_bytes)
break;
else if(write_bytes > 0)
{
ptr += write_bytes;
read_bytes -= write_bytes;
}
}
if(write_bytes == -1)
break;
}
}
close(from_fd);
close(to_fd);
exit(0);
}

 

能实现将一个存在的文件中的内容读到另外一个文件当中,另外一个文件不存在时将进行创建!

心得:注意注释的那一句,将被写入的那个文件打开的时候应该设置o_WRONLY的属性,如果设置成了O_RDONLY,内容将写不进入

你可能感兴趣的:(文件)