ftruncate函数的使用

ftruncate函数用于截断文件到指定长度。当文件被缩短时,超出指定长度的数据将被丢弃。简单示例展示了如何从前和从后截取文件内容,需要注意不同系统中行结束符的差异,如POSIX的LF和Windows的CR/LF。

##本能功能
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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JXES智能生态系统

如文章对你有用,请作者喝个咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值