Peter 时光机

追求卓越,成功便会不期而至。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

这些天学习《UNIX环境高级编程》,里面提及到一种空洞文件,即文件中间有大量空洞,'\0'的字符填充。

生成的代码如下

#include <fcntl.h>
#include <apue.h>

int main()
{
    int fd;
    if((fd = creat("file.hole",FILE_MODE))<0)
      printf("Wrong!");

    write(fd,"file hole\n",9);
    lseek(fd,1234,SEEK_SET);
    write(fd,"hello,world\n",11);

    exit(0);
}

 

然后问题来了。

Q:编写一个类似CP命令的程序,它复制包含空洞的文件,但不将字节0写到输出文件去。

A:思路比较简单,就是打开文件以后,一个字符一个字符的读,如果是'\0'就跳过,否则就拷贝到新文件中。好久没有进行文件I/O的操作了,所以有点生疏,用了半个多小时才完成,ubuntu下gcc编译通过。

/*
 * =====================================================================================
 *
 *       Filename:  reader.c
 *
 *    Description:  copy file but leave the hole alone.
 *
 *        Version:  1.0
 *        Created:  Tuesday, May 01, 2012 02:43:11 CST
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Peter Shih (), shihty5@163.com
 *        Company:  UESTC
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE * in_fd;
    FILE * out_fd;
    int ch;
    
    if(argc != 3)
    {
        printf("usage: %s source destination \n", *argv);
        exit(1);
    }
    
    if((in_fd = fopen(argv[1],"r"))==NULL)
    {
        perror(argv[1]);
        exit(1);
    }
    
    if((out_fd = fopen(argv[2],"wt"))==NULL)
    {
        perror(argv[2]);
        exit(1);
    }

    ch = fgetc(in_fd);
    while(ch!=EOF)
    {
        if(ch!='\0') 
          fputc(ch,out_fd);
        ch = fgetc(in_fd);
    }

    fclose(in_fd);
    fclose(out_fd);
}
posted on 2012-05-01 15:39  Peter 时光机  阅读(806)  评论(1编辑  收藏  举报