Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4733253
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2009-05-25 09:25:42

  看到论坛有个帖子问如何高效率删除文件最后一行,当然
   sed -i '$d' urfile
   :|dd of=urfile seek=1 bs=$(($(stat -c%s urfile)-$(tail -1 urfile|wc -c)))
   dd这个速度已经很快了,很猛
   说到底这些命令最后还是用c,所以用c写了个
  
  

[root@localhost truncate]# cat last_d.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>

#define GUESS_LINE_SIZE 80

//这里假设最后一行的长度最大只能为80

int get_line_size(char *ptr);

int
main(int argc, char *argv[])
{
        char buf[GUESS_LINE_SIZE];
        int line_len, fd;
        struct stat stat_buf;
       
        if ((fd = open(argv[1], O_RDWR)) < 0) {
                printf("open error!\n");

                return -1;
        }
       
        if (lstat(argv[1], &stat_buf) < 0) {
                printf("lstat error!\n");

                return -1;
        }
       
        if (lseek(fd, -GUESS_LINE_SIZE, SEEK_END) < 0) {
                printf("lseek error!\n");

                return -1;           

       }
       
        if (read(fd, buf, GUESS_LINE_SIZE) < 0) {
                printf("read error!\n");

                return -1;
        }
       
        line_len = get_line_size(buf);
        //printf("line_len = %d\n", line_len);

        if (truncate(argv[1], stat_buf.st_size - line_len) < 0) {
                printf("truncate error!\n");

                return -1;
        }
       
        return 0;
}

int
get_line_size(char *ptr)
{
    int line_len = 0;
    int i = GUESS_LINE_SIZE - 2;
       
        while (*(ptr + i) != '\n') {
                //printf("%c", *(ptr + i));

                i--;
                line_len++;
        }
     return line_len;
}

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