##本能功能
ftruncate( )
NAME
ftruncate( ) - truncate a file (POSIX)
SYNOPSIS
int ftruncate
(
int fildes, /* fd of file to truncate /
off_t length / length to truncate file */
)
DESCRIPTION
This routine truncates a file to a specified size.
RETURNS
0 (OK) or -1 (ERROR) if unable to truncate file.
简单理解就是会把文件前面length长度的内容截取出来,而把剩下长度的内容丢掉。
- 栗子
int main(int argc, char *argv[])
{
int fd = open(argv[1], O_RDWR);
ftruncate(fd, 18); //截取长度为18的内容
close(fd);
}
假设test.txt的内容:
abcd1 //一行长度是5+1=6,因为最后有一个换行符\n
abcd2
abcd3
abcd4
abcd5
$./test test.txt
执行后,test.txt中的内容:
abcd1
abcd2
abcd3
##从后向前截取
#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);
}
$./test test.txt 0 18
abcd3
abcd4
abcd5
以上两种使用情形,需要注意每行的结束符,一般POSIX是LF,而windows是CR/LF.
ftruncate函数用于截断文件到指定长度。当文件被缩短时,超出指定长度的数据将被丢弃。简单示例展示了如何从前和从后截取文件内容,需要注意不同系统中行结束符的差异,如POSIX的LF和Windows的CR/LF。
931

被折叠的 条评论
为什么被折叠?



