- 论坛徽章:
- 0
|
感觉用c写效率应该是最高的,不过本人的程序显然没有达到最高的效率,用800M的文件测试了一下,
real 0m0.002s
user 0m0.000s
sys 0m0.000s
代码如下:本代码基于这样的假设,文本中最长的行不超过80个字符。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#define GUESS_LINE_SIZE 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");
}
if (lstat(argv[1], &stat_buf) < 0) {
printf("lstat error!\n");
}
if (lseek(fd, -GUESS_LINE_SIZE, SEEK_END) < 0) {
printf("lseek error!\n");
}
if (read(fd, buf, GUESS_LINE_SIZE) < 0) {
printf("read error!\n");
}
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");
}
exit(0);
}
int
get_line_size(char *ptr)
{
int line_len = 0, i = GUESS_LINE_SIZE - 2;/*buf中的最后一个字符为'\n'*/
while (*(ptr + i) != '\n') {
//printf("%c", *(ptr + i));
i--;
line_len++;
}
return line_len;
} |
|