- 论坛徽章:
- 0
|
原帖由 大于连 于 2009-5-30 12:47 发表 ![]()
打开文件 定位到文件尾 如字符不为换行符 则删除之 不就OK了?
难道实现这个很困难?
代码如下:本代码基于这样的假设,文本中最后一行的长度不超过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;
} |
|
|