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

查看:262
本文介绍了在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\n");
    memset(page, 'A', 4096);
    write(fd, page, 4096);

    // Page B
    printf("Write page B\n");
    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\n", ret);

    close(fd);
    free(page);

    return (0);
}

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

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