标签:target eth little targe for logger not span asi
This is a homework of unix class which is all about copy a file, not the TCP(Transmission Control Protocol).
Base on read(), write(), lseek() and open() methods to copy a file under unix enviroment. This is an example:
tcp file1 file2 (./a.out file2 file2)
tcp file1 dir
tcp file1 dir/file2
If target is a file, then copy the source into target file. If target is a directory file1 would copyed into this dir.
Copy a file via mmap() and memcpy() instead of read() and write() to make the same usage like tcp.
1. copy file1 to file2
2. if argv[2] is a dir, copy file1 into this dir.
And make sure before read/write you have make sure the files are opened.
while((read_size = read(fd_src_file, n, BUFFSIEZ)) > 0){ if ((write_size = write(fd_dest_file, n, read_size)) != read_size){ perror("write dest_file fail"); exit(1); } }
Change avg[2] from "/User/.../Desktop" to "/User/.../Desktop/file2".
This method is not the perfect, even a little bit funny. If you have a better idea you can tell me.
if (S_ISDIR(buf.st_mode)){ // change the directory if file copy path is not current dir sprintf(copy_file_name,"%s%s%s",argv[2],"/",argv[1]); printf("change dir to %s\n", copy_file_name); }
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <string.h> #define BUFFSIEZ 512 int main(int argc, char const *argv[]) { int fd_src_file, fd_dest_file; int read_size, write_size; char n[BUFFSIEZ]; char copy_file_name[50]; struct stat buf; // check input if (argc != 3){ printf("a.out src_file to dest_file...\n"); exit(1); } strcpy(copy_file_name, argv[2]); if (lstat(argv[2], &buf) < 0) { perror("lstat error"); } if ((fd_src_file = open(argv[1],O_RDWR,0774)) < 0) { perror("open src_file fail"); exit(1); } else printf("open file ok.\n"); if (S_ISDIR(buf.st_mode)){ // change the directory if file copy path is not current dir sprintf(copy_file_name,"%s%s%s",argv[2],"/",argv[1]); printf("change dir to %s\n", copy_file_name); } if ((fd_dest_file = open(copy_file_name,O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR,0600)) < 0){ perror("create dest_file fail"); exit(1); } while((read_size = read(fd_src_file, n, BUFFSIEZ)) > 0){ if ((write_size = write(fd_dest_file, n, read_size)) != read_size){ perror("write dest_file fail"); exit(1); } } if (read_size < 0) { fprintf(stderr, "read error\n"); exit(1); } printf("read/write ok\n"); return 0; }
Search for mmap() and memcpy is the best way to understand how do these method works. Here is a better blog which introduces using mmap() to copy a file.
http://blog.chinaunix.net/uid-20662363-id-1904142.html
Only when I start to write did I understang the patient I have to pay for my blogs. Greet to all those great tech-bloggers!
标签:target eth little targe for logger not span asi
原文地址:http://www.cnblogs.com/22Kon/p/6713387.html