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);
}
智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告