In Linux, copy files in C language-general Linux technology-Linux programming and kernel information. The following is a detailed description. /*
Function: copy file from file1 to file2
How to execute:./copyfile file1 file2 (under Linux)
Data: 2007-05-09
*/
# Include /* Fprintf (), stderr, BUFSIZ */
# Include /**/
# Include /* Stderror ()*/
# Include /* Open (), flag */
# Include /* Errno */
# Include /* Ssize_t */
# Include
# Include /* Mode_t */
# Define BUFFER_SIZE 3
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 the source file */
If (from_fd = open (argv [1], O_RDONLY) =-1)/* open file readonly, return-1 indicates an error; otherwise, return the file descriptor */
{
Fprintf (stderr, "Open % s Error: % s \ n", argv [1], strerror (errno ));
Exit (1 );
}
/* Create the target file */
/* The O_CREAT option is used to create a file. The open () function requires 3rd parameters,
Mode = S_IRUSR | S_IWUSR indicates S_IRUSR users can read S_IWUSR users can write */
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 file code */
While (bytes_read = read (from_fd, buffer, BUFFER_SIZE ))
{
/* A fatal error 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 occurred */
If (bytes_write =-1) & (errno! = EINTR ))
Break;
/* All read bytes have been written */
Else if (bytes_write = bytes_read)
Break;
/* Write only a part and continue writing */
Else if (bytes_write> 0)
{
Ptr + = bytes_write;
Bytes_read-= bytes_write;
}
}
/* Fatal error during write */
If (bytes_write =-1)
Break;
}
}
Close (from_fd );
Close (to_fd );
Return;
}
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.