实现文件拷贝,之前写的如果文件内容大于200字节就复制不了,现在优化了代码,避免了内存空间的浪费,也不会出现复制内容太大而溢出。
1 //实现文件复制 ,。
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <sys/stat.h>
7 #include <sys/types.h>
8 #include <fcntl.h>
9 #include <string.h>
10
11 int main(int argc, char *argv[])
12 {
13 int fd1,fd2;
14
15 fd1 = open(argv[1],O_RDWR);
16 printf("fd1 = %d\nargv[1] = %s\n",fd1,argv[1]);
17 fd2 = open(argv[2], O_RDWR | O_CREAT, 0666);
18 printf("fd2 = %d\nargv[2] = %s\n",fd2,argv[2]);
19 //先把文件偏移量移到文件末尾,返回文件内容大小,然后再使文件偏移量移
到文件头,以便读取文件内容
20 int b = lseek(fd1, 0, SEEK_END);
21 lseek(fd1, 0, SEEK_SET);
22
23 char buff[b];
24 memset(buff,0,sizeof(buff));
25
26 read(fd1, buff,b);
27 printf("buff = %s",buff);
28 printf("\nb = %d",b);
29 write(fd2,buff,b);
30
31 close(fd1);
32 close(fd2);
33
34 return 0;
35 }
~
7月18号优化:
实现文件复制,如果文件内容大于5个字节,则循环每次先复制5个字节,一直到复制完
/*实现文件复制,如果文件内容大于5个字节,则循环每次先复制5个字节,一直到复制完*/
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <sys/stat.h>
7 #include <sys/types.h>
8 #include <fcntl.h>
9 #include <string.h>
10 #include <assert.h>
11
12 //#define BUFFSIZE 1024
13
14 int main(int argc, char *argv[])
15 {
16 int fd1,fd2;
17 int b;
18 char buff[5] ;
19
20 fd1 = open(argv[1],O_RDWR);
21 printf("fd1 = %d\nargv[1] = %s\n",fd1,argv[1]);
22 fd2 = open(argv[2], O_RDWR | O_CREAT, 0666);
23 printf("fd2 = %d\nargv[2] = %s\n",fd2,argv[2]);
24
25 //先把文件偏移量移到文件末尾,返回文件内容大小,然后再使文件偏移量移
到文件头,以便读取文件内容
26 b = lseek(fd1, 0, SEEK_END);
27 lseek(fd1, 0, SEEK_SET);
28 printf("要复制的文件大小为b = %d\n",b);
29 printf("要复制打文件内容为:");
30
31 //如果复制内容大于5字节,则每一次复制5个字节,一直到复制完
32 while(b>0 && b>=5)
33 {
34 read(fd1, buff, sizeof(buff));
35 write(fd2,buff,sizeof(buff));
36 printf("%s",buff);
37 b -=5;
38 }
39
40
41 // printf("这是个空文件\n");
42
43 close(fd1);
44 close(fd2);
45
46 return 0;
47 }
运行结果截图