学习ING

linux c截断文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char **argv)
{
if ( argc != 4 )
{
printf("Usage %s file_name offset length\n", argv[0]);
return -1;
}
off_t offset = atoi(argv[2]);
off_t length = atoi(argv[3]);
if ( offset < 0 || length < 0 )
{
return -1;
}
int fd = open(argv[1], O_RDWR);
if ( fd < 0 )
{
perror("open");
return -1;
}
off_t file_len = lseek(fd, 0, SEEK_END);
lseek(fd, offset + length, SEEK_SET);
char buff[1024];
int n;
while ( (n = read(fd, buff, 1024)) != 0 )
{
if ( n < 0 )
{
if ( errno == EINTR )
continue ;
else
break;
}
lseek(fd, - (length + n), SEEK_CUR);
write(fd, buff, n);
lseek(fd, (length), SEEK_CUR);
}
ftruncate(fd, file_len - length);
close(fd);
}
posted @ 2010-08-24 17:54  祝雄锋  阅读(3842)  评论(0编辑  收藏  举报