正在加载……
专注、离线、切勿分心

文件定位

函数 lseek() 将文件指针设定到相对于 whence ,偏移值为 offset 的位置

#include <sys/types.h>
#include <unistd.h>
off_t  lseek(int fd,  off_t offset,  int whence);   //fd文件描述词

whence 可以是下面三个常量的一个:
SEEK_SET  从文件头开始计算
SEEK_CUR  从当前指针开始计算
SEEK_END  从文件尾开始计算

利用该函数可以实现文件空洞(对一个新建的空文件,可以定位到偏移文件开头1024个节的地方,再写入一个字符(可以是换行或者"\0"),则相当于给该文件分配了1025个字节的空间,形成文件空洞)通常用于多进程间通信的时候的共享内存。


test.c
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
int main()
{
    int fd = open("c.txt", O_WRONLY | O_CREAT,0666);
//  int fd = open("./c.txt", O_WRONLY);
    lseek(fd, 10, SEEK_SET);
    write(fd, "a", 1);    //"a",必须是双引号,代表一个字符串常量的首地址,不能使‘’
   // write(fd,"\0",1);   //这样写用在多进程通信
    close(fd);
    return 0;
}

// c.txt 的文件大小现在是11 





test.c
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
int main(int argc,char **argv)
{
        int fd = open(argv[1],O_RDWR);
        char buf[128];
        read(fd,buf,2);
        printf("buf =%s\n",buf);
        strcpy(buf,",world!");
        lseek(fd,0,SEEK_SET);  //偏移到文件开头,产生覆盖
        write(fd,buf,strlen(buf));
        close(fd);
        return 0;
}


posted on 2018-02-08 10:19  正在加载……  阅读(620)  评论(0编辑  收藏  举报