C Implement file copy

Source: Internet
Author: User
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main (int argc,char** argv)
{
int from_fd,to_fd;
int bytes_read,bytes_write;
Char Buffer[buffer_size];
char* ptr;
if (argc!= 3)
{
fprintf (stderr, "Usage:%s fromfile tofile\n\a", argv[0]);
Exit (1);
}
/* Open source file * *
if ((from_fd = open (argv[1],o_rdonly)) = = 1)
{
fprintf (stderr, "Open%s Error:%s\n", Argv[1],strerror (errno));
Exit (1);
}
/* Create destination file * *
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);
}
/* The following code is a classic copy of the file code * * *
while (Bytes_read = Read (from_fd,buffer,buffer_size))
{
* * A fatal error has occurred.
if ((Bytes_read = = 1) && (errno!= eintr)) break;
else if (Bytes_read > 0)
{
ptr = buffer;
while (Bytes_write = Write (To_fd,ptr,bytes_read))
{
* * A fatal error has occurred.
if ((Bytes_write = = 1) && (errno!= eintr)) break;
/* All read bytes have been written/*
else if (Bytes_write = = bytes_read) break;
/* Only write a part, continue to write * *
else if (Bytes_write > 0)
{
PTR + = Bytes_write;
Bytes_read-= Bytes_write;
}
}
/* A fatal error occurred when writing * *
if (Bytes_write = = 1) break;
}
}
Close (FROM_FD);
Close (TO_FD);
Exit (0);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.