【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,则文件为增加到这个大小; 否则将保留文件大小不变。

 1 #include <fcntl.h>
 2 #include <stdio.h>
 3 #include <errno.h>
 4 #include <string.h>
 5 #include <unistd.h>
 6 #include <stdint.h>
 7 
 8 uint64_t file_size = 10 * 1024 * 1024 * 1024ULL;
 9 
10 int main()
11 {
12   int fd = open("tmp.txt", O_CREAT | O_RDWR, 0666);
13   if (fd < 0)
14   {
15     printf("fd < 0");
16     return -1;
17   }
18 
19   int ret = posix_fallocate(fd, 0, file_size);
20   if (ret < 0)
21   {
22     printf("ret = %d, errno = %d,  %s\n", ret, errno, strerror(errno));
23     return -1;
24   }
25 
26   printf("fallocate create %.2fG file\n", file_size / 1024 / 1024 / 1024.0);
27 
28   close(fd);
29   return 0;
30 }

输出:

参考资料

1. posix_fallocate(3) 【Linux manual page】

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

原文地址:https://www.cnblogs.com/sunbines/p/15652150.html