zoukankan      html  css  js  c++  java
  • [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
    ");
    26         exit(1);
    27     }
    28     if ((fd2=creat("file.2",FILE_MODE))<0) {
    29         printf("creat error
    ");
    30         exit(1);
    31     }
    32 
    33     if (write(fd1,buf1,10)!=10) {
    34         printf("buf1 write error
    ");
    35         exit(1);
    36     }
    37     if (write(fd2,buf2,10)!=10) {
    38         printf("buf2 write error
    ");
    39         exit(1);
    40     }
    41 
    42     if (lseek(fd2,0,SEEK_SET)==-1) {
    43         printf("lseek error
    ");
    44         exit(1);
    45     }
    46     fd2=open("file.2",O_RDONLY);
    47     if (read(fd2,buf3,10)==-1) {
    48         printf("file2 get error
    ");
    49         exit(1);
    50     }
    51     if (lseek(fd1,0,SEEK_END)==-1) {
    52         printf("lseek error
    ");
    53         exit(1);
    54     }
    55     if (write(fd1,buf3,10)!=10) {
    56         printf("buf3 write error
    ");
    57         exit(1);
    58     }
    59     exit(0);
    60 }

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

  • 相关阅读:
    Git和SVN之间的五个基本区别
    如何成为一名程序员:我的道路
    产品经理要懂多少技术?
    Unix哲学相关资源汇总
    Android.mk简介
    Android 中的 Service 全面总结
    获取Map集合中数据的方法
    少编码多思考:代码越多 问题越多
    【自定义Android带图片和文字的ImageButton】
    Android task process thread 进程与线程
  • 原文地址:https://www.cnblogs.com/zxysmalleyes/p/5321207.html
Copyright © 2011-2022 走看看