[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)

转载于:https://www.cnblogs.com/zxysmalleyes/p/5321207.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值