2012年(47)
分类: LINUX
2012-09-20 16:37:12
#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;
fd = open(argv[1], O_RDWR);
lstat(argv[1], &stat_buf);
lseek(fd, -GUESS_LINE_SIZE, SEEK_END);
read(fd, buf, GUESS_LINE_SIZE) ;
line_len = get_line_size(buf);
truncate(argv[1], stat_buf.st_size - line_len);
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;
}