- Lab 4-1: File copy
Familiar with Linux system IO programming
?
- Experimental requirements:
1, according to the interface given by IO.h to implement the general IO operation interface
?
2. The mycpy file Copy tool is completed using IO operation interface:
The file copy function is completed by redirection:./mycpy < Srcfile > Desfile
?
1. Experiment Code:
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.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 the code of a classic copy file */
while (Bytes_read=read (from_fd,buffer,buffer_size)) {
if ((bytes_read==-1) && (ERRNO!=EINTR)) break; /* Read error occurred, exit Loop */
else if (bytes_read>0) {
Ptr=buffer;
while (Bytes_write=write (To_fd,ptr,bytes_read)) {
if ((bytes_write==-1) && (ERRNO!=EINTR)) break; /* If you write an error, exit the loop */
/* Write down all read bytes */
else if (bytes_write==bytes_read) break;/* Read and write section not equal to exit loop */
else if (bytes_write>0) {/* Write only a portion, continue writing */
Ptr+=bytes_write;
Bytes_read-=bytes_write;
}
}
if (bytes_write==-1) break; /* Fatal error occurred while writing */
}
}
Close (FROM_FD);
Close (TO_FD);
Exit (0);
}
?
2. Compiling
3, before the operation:
[Email protected]:~/desktop#./copyfile main.c hello.c
?
?
?
After execution:
Successful copy.
Experiment Experience:
???? This is the first experiment in the Linux file operation: A copy of the file is implemented in the lab's operating system. The above is the result of my experiment. The whole process was very smooth. Thank you.
?
5.7 File copy