[Linux]用lseek拼接两个文件

实验作业要求:用lseek拼接两个文件

这个程序的实现方法应该有很多,我贴一下自己的版本。

思路:

1、创建两个文件,并分别向其中写入两个字符串

2、利用lseek将指针移到第二个文件的开头,然后读取第二个文件的内容,存储在字符串3中

3、利用lseek将指针移到第一个文件的末尾,然后将刚刚读取的字符串写入

 1 //lab_lseek.c
 2 //By ShannonZhang
 3 //2016-03-18
 4 
 5 #include <sys/types.h>
 6 #include <fcntl.h>
 7 #include <unistd.h>
 8 #include <stdio.h>
 9 
10 char buf1[]="abcdefile1"
11 //buf1 has 10 letters
12 char buf2[]=" ABCDfile2";
13 //buf2 also has 10 letters
14 char buf3[10];
15 //buf3 is used for containing the read string
16 
17 #define FILE_MODE 0644
18 
19 int main(void)
20 {
21     int fd1;
22     int fd2;
23 
24     if ((fd1=creat("file.1",FILE_MODE))<0) {
25         printf("creat error\n");
26         exit(1);
27     }
28     if ((fd2=creat("file.2",FILE_MODE))<0) {
29         printf("creat error\n");
30         exit(1);
31     }
32 
33     if (write(fd1,buf1,10)!=10) {
34         printf("buf1 write error\n");
35         exit(1);
36     }
37     if (write(fd2,buf2,10)!=10) {
38         printf("buf2 write error\n");
39         exit(1);
40     }
41 
42     if (lseek(fd2,0,SEEK_SET)==-1) {
43         printf("lseek error\n");
44         exit(1);
45     }
46     fd2=open("file.2",O_RDONLY);
47     if (read(fd2,buf3,10)==-1) {
48         printf("file2 get error\n");
49         exit(1);
50     }
51     if (lseek(fd1,0,SEEK_END)==-1) {
52         printf("lseek error\n");
53         exit(1);
54     }
55     if (write(fd1,buf3,10)!=10) {
56         printf("buf3 write error\n");
57         exit(1);
58     }
59     exit(0);
60 }

程序运行后,file.1里的内容应该是buf1+buf3(也就是读取的buf2)

posted on 2016-03-25 21:17  小眼儿是挨踢人士  阅读(990)  评论(0编辑  收藏  举报

导航