在 linux 中截断文件的前 100MB [英] Truncating the first 100MB of a file in linux

查看:22
本文介绍了在 linux 中截断文件的前 100MB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指的是 如何用很少的空闲磁盘空间连接两个大文件?

我正在实施以下内容:

  1. 分配一个合并大小的稀疏文件.
  2. 从第二个文件的末尾复制 100Mb 到新文件的末尾.
  3. 截断第二个文件末尾的 100Mb
  4. 循环 2&3,直到完成第二个文件(将 2. 修改为目标文件中的正确位置).
  5. 使用第一个文件执行 2&3&4.

我想知道是否有人能够在 linux 中截断"给定文件?截断是按文件大小进行的,例如,如果文件为 10GB,我想截断文件的前 100MB,并保留剩余的 9.9GB.有人可以帮忙吗?

I would like to know if is there anyone there who are able to "truncate" a given file in linux? The truncation is by file size, for example if the file is 10GB, I would like to truncate the first 100MB of the file and leave the file with remaining 9.9GB. Anyone could help in this?

谢谢

推荐答案

回答,现在 Linux 内核 v3.15 (ext4/xfs) 实现了

Answer, now this is reality with Linux kernel v3.15 (ext4/xfs)

在这里阅读http://man7.org/linux/man-pages/man2/fallocate.2.html

测试代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>

#ifndef FALLOC_FL_COLLAPSE_RANGE
#define FALLOC_FL_COLLAPSE_RANGE        0x08
#endif

int main(int argc, const char * argv[])
{
    int ret;
    char * page = malloc(4096);
    int fd = open("test.txt", O_CREAT | O_TRUNC | O_RDWR, 0644);

    if (fd == -1) {
        free(page);
        return (-1);
    }

    // Page A
    printf("Write page A
");
    memset(page, 'A', 4096);
    write(fd, page, 4096);

    // Page B
    printf("Write page B
");
    memset(page, 'B', 4096);
    write(fd, page, 4096);

    // Remove page A
    ret = fallocate(fd, FALLOC_FL_COLLAPSE_RANGE, 0, 4096);
    printf("Page A should be removed, ret = %d
", ret);

    close(fd);
    free(page);

    return (0);
}

这篇关于在 linux 中截断文件的前 100MB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆