LDD3源码分析之llseek分析(二)

来源:互联网 发布:杭州g20知乎 编辑:程序博客网 时间:2024/04/26 18:46

一  对llseek做了不同的分析:

    

 #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #define BUF_SIZE 50 #define DEVICE_FILE "test.c"int main(int argc, char *argv[]){    int fd;    int num;    char buf[BUF_SIZE];    fd = open(DEVICE_FILE, O_RDWR);    if(fd < 0)    {       printf("open scull error!\n");        return -1;    }    memset(buf, 0, BUF_SIZE);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 2, SEEK_SET);    write(fd, "aa", 2);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 2, SEEK_SET);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 0, SEEK_SET);    lseek(fd, 2, SEEK_CUR);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 0, SEEK_SET);    lseek(fd, 0, SEEK_END);    memset(buf, 0, BUF_SIZE);    printf("read return value is %d.\n", read(fd, buf, BUF_SIZE));    return 0;}
得出的打印结果:



2  代码: 

 #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #define BUF_SIZE 50 #define DEVICE_FILE "test.c"int main(int argc, char *argv[]){    int fd;    int num;    char buf[BUF_SIZE];    fd = open(DEVICE_FILE, O_RDWR);    if(fd < 0)    {       printf("open scull error!\n");        return -1;    }    memset(buf, 0, BUF_SIZE);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 2, SEEK_SET); /*   write(fd, "aa", 2);  */    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);write(fd,"aa",2);    lseek(fd, 2, SEEK_SET);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 0, SEEK_SET);    lseek(fd, 2, SEEK_CUR);    num = read(fd, buf, BUF_SIZE);    buf[num] = 0;    printf("%s\n", buf);    lseek(fd, 0, SEEK_SET);    lseek(fd, 0, SEEK_END);    memset(buf, 0, BUF_SIZE);    printf("read return value is %d.\n", read(fd, buf, BUF_SIZE));    return 0;}
运行结果:


     

原创粉丝点击