Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1741871
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: LINUX

2015-10-28 09:42:31

先来看看如何在shell下创建空洞文件

点击(此处)折叠或打开

  1. dd if=/dev/zero of=/1k.file bs=1k count=1 seek=9
使用lseek则如下,apue上的例子跟这个倒也差不多。

点击(此处)折叠或打开

  1. #include <apue.h>

  2. int main(int argc, char *argv[])
  3. {
  4.     int fd;
  5.     char buffer[]="this begins";
  6.     char enddata[]="this ends!";

  7.     // create a new file named file_with_hold in the pwd
  8.     if((fd=creat("file_with_hole",0644))<0)
  9.         exit(1);

  10.     //put a small string at the beginning
  11.     if(write(fd,buffer,10)!=10)
  12.         exit(1);

  13.     //seek 131072=2**17 bytes past the beginning
  14.     if(lseek(fd,131072,SEEK_SET)==-1)
  15.         exit(1);

  16.     // write a small string there as well
  17.     if(write(fd,enddata,10)!=10)
  18.         exit(1);

  19.     // we now have a large file with a big hole
  20.     exit(0);
  21.     }
然后查看下文件内容:

点击(此处)折叠或打开

  1. od -c file_with_hole 
  2. 0000000 t h i s b e g i n \0 \0 \0 \0 \0 \0
  3. 0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
  4. *
  5. 0400000 t h i s e n d s !
  6. 0400012
然后用另外一个程序删除这个文件

点击(此处)折叠或打开

  1. ./unlinkdemo ./ file_with_hole

点击(此处)折叠或打开

  1. #include <apue.h>
  2. #include <fcntl.h>
  3. /* Usage: unlinkat demo directory file 
  4. where path is the path to a file relative to the 
  5. given directory
  6. */

  7. int main(int argc, char *argv[])
  8. {
  9.     int dirfd;

  10.     /* check args */
  11.     if(argc < 3){
  12.         fprintf(stderr,"usage: %s directory file\n",*argv);
  13.         exit(1);
  14.         }

  15.     /* open directory */
  16.     if((dirfd=open(argv[1],O_RDONLY))==-1){
  17.         fprintf(stderr,"could not open %s\n",argv[1]);
  18.         exit(1);
  19.         }

  20.     /* we could check here if argv[2] refers to a directory or a file
  21.     to make this more robust , but we do not */
  22.     /*unlink the file relative to dirfd */
  23.     if(-1==unlinkat(dirfd,argv[2],0)){
  24.         fprintf(stderr,"could not unlink %s/%s\n",argv[1],argv[2]);
  25.         exit(1);
  26.         }
  27.     return 0;
  28.     }


阅读(1325) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~