【linux编程】预分配磁盘空间

预分配磁盘空间

我们在开发程序的过程中,往往需要预分配磁盘空间,防止因磁盘空间不够而引发程序异常问题(已踩过坑), 现网查阅资料,有些预分配磁盘空间的方法不正确。

 

1.1 posix_fallocate函数

函数原型:

#include <fcntl.h>
int posix_fallocate(int fd, off_t offset, off_t len);

 

说明:函数posix_fallocate()确保磁盘空间为分配给文件描述符fd所引用的文件从offset开始并继续len的范围内的字节字节。在成功调用posix_fallocate()之后,可以确保写入指定范围内的字节不会因为磁盘空间不足导致失败。

 如果文件的大小小于offset+len,则文件为增加到这个大小; 否则将保留文件大小不变。

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>

uint64_t file_size = 10 * 1024 * 1024 * 1024ULL;

int main()
{
  int fd = open("tmp.txt", O_CREAT | O_RDWR, 0666);
  if (fd < 0) {
    printf("fd < 0");
    return -1;
  }

  int ret = posix_fallocate(fd, 0, file_size);
  if (ret < 0) {
    printf("ret = %d, errno = %d,  %s\n", ret, errno, strerror(errno));
    return -1;
  }

  printf("fallocate create %.2fG file\n", file_size / 1024 / 1024 / 1024.0);
  close(fd);
  return 0;
}

输出:

 

参考资料

1. posix_fallocate(3) 【Linux manual page】

2.Linux创造固定的文件大小-预分配磁盘空间

posted @ 2021-12-06 22:13  苏格拉底的落泪  阅读(612)  评论(0编辑  收藏  举报