1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 int main ()
8 {
9 size_t tmp;
10 int fd1,fd2;
11 char buf[1024];
12 fd1 = open("/home/xuptlinux/v.c",O_RDONLY,0);
13 tmp = read(fd1,buf,1024);
14 buf[tmp] = '\0';
15 printf("%d\n %d\n %s\n",fd1,tmp,buf);
16 fd2 = open("/home/xuptlinux/mylinux",O_WRONLY|O_TRUNC,0600);
17 if ( write(fd2,buf,strlen(buf))==-1){
18 printf("write error/!\n");
19 }
20 printf("%d\n",fd2);
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 void my_err(const char *err_string,int line)
9 {
10 fprintf(stderr,"line:%d",line);
11 perror(err_string);
12 exit(1);
13 }
14 int main ()
15 {
16 int len,i;
17 int ret;
18 int fd1,fd2;
19 char read_buf[1024];
20 if((fd1=open("/home/xuptlinux/v.c",O_RDONLY,0))==-1)
21 my_err("open",__LINE__);
22 else
23 {
24 printf("creat file success!\n");
25
26 }
27 if((lseek(fd1,0,SEEK_END))==-1)
28 {
29 my_err("lseek",__LINE__);
30 }
31 if((len=lseek(fd1,0,SEEK_CUR))==-1)
32 {
33 my_err("lseek",__LINE__);
34 }
35 if((lseek(fd1,0,SEEK_SET))==-1)
36 {
37 my_err("lseek",__LINE__);
38 }
39 printf("len:%d\n",len);
40 if((ret=read(fd1,read_buf,len))<0)
41 my_err("read",__LINE__);
42 read_buf[ret]='\0';
43 printf("%s\n",read_buf);
44 if((fd2 = open("/home/xuptlinux/mylinux",O_WRONLY|O_TRUNC,0600))==-1)
45 printf("error1\n");
46 if(write(fd2,read_buf,ret)==-1)
47 printf("error2\n");
48 printf("%d\n",fd2);
49 close(fd1);
50 close(fd2);
51 printf("copy success!\n");
52 return 0;
53 }
改为命令模式
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 void my_err(const char *err_string,int line)
9 {
10 fprintf(stderr,"line:%d",line);
11 perror(err_string);
12 exit(1);
13 }
14 int main ( int arg,char *argv[] )
15 {
16 int len,i;
17 int ret;
18 int fd1,fd2;
19 char read_buf[1024];
20 if(arg<2)
21 {
21 {
22 printf("%s
\n",argv[0]); 23 exit(0);
24 }
25 if((fd1=open(argv[1],O_RDONLY,0))==-1)
26 my_err("open",__LINE__);
27 else
28 {
29 printf("creat file success!\n");
30
31 }
32 if((lseek(fd1,0,SEEK_END))==-1)
33 {
34 my_err("lseek",__LINE__);
35 }
36 if((len=lseek(fd1,0,SEEK_CUR))==-1)
37 {
38 my_err("lseek",__LINE__);
39 }
40 if((lseek(fd1,0,SEEK_SET))==-1)
41 {
42 my_err("lseek",__LINE__);
43 }
44 printf("len:%d\n",len);
45 if((ret=read(fd1,read_buf,len))<0)
46 my_err("read",__LINE__);
47 read_buf[ret]='\0';
48 fd2= open(argv[2],O_WRONLY|O_TRUNC,0600);
49 if(write(fd2,read_buf,ret)==-1)
50 my_err("write",__LINE__);
51 printf("%d\n",fd2);
52 close(fd1);
53 close(fd2);
54 printf("copy success!\n");
55 return 0;
56 }
当然一个拷贝代码没这么简单,据说完整的代码在300行以上,那就实现了很多文件操作。期待自己什么时候能做好。