基于fallocate为文件打洞

本文详细描述了如何使用C语言在LinuxAARCH64平台上编写一个程序,实现创建大文件并预留特定区域的操作,包括动态分配内存、写入数据、以及使用fallocate函数预留空间。
摘要由CSDN通过智能技术生成

code

#define _GNU_SOURCE
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include <sys/types.h>
//#include <string>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <linux/falloc.h>
//using namespace std;

int main(int argc, char *argv[])
{
    long blocks = atoi(argv[1]);
    long SIZE = 4096 * blocks;
    long rec_len = 512*1024;
    long num_rec = SIZE/rec_len;
    long rest_size = SIZE - (rec_len*num_rec);
    char* buf;
    long i = 0;
    long offset=0;
    long len=8192;
    mode_t f_attrib = S_IRUSR|S_IWUSR;
    int fd_ret=open("./1.qwj",O_RDWR|O_CREAT, f_attrib);
    if(fd_ret<0)
        perror("creat file fail");
    else{
        lseek(fd_ret, 0, SEEK_END);

        buf = malloc(512*1024);
        memset(buf, 0xcafe, 512*1024);
        //printf("%ld\n",num_rec);
        for(i=0; i<num_rec; i++)
        {
            write(fd_ret, buf, rec_len);
        }

        if(rest_size)
        {
            write(fd_ret, buf, rest_size);
        }
        fsync(fd_ret);
        free(buf);
        printf("Write OK\n");
    }
    i=0;
    //在i偏移的位置上打一个4k大小的洞
    while (i < SIZE){
        if(fallocate(fd_ret,FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, i, 4096)<0)
            perror("could not deallocate");
        i = i + len;
    }
    printf("fallocate OK\n");
    return 0;
}

2.交叉编译

aarch64-linux-gnu-gcc -static  write_bigfile.c
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值