[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;
}
|