| |

How to Get Available Filesystem Space on Linux: a C Function with a C++ Example

It is common for programs to write to files in filesystems on disks. However, what if the disk was almost full when your program writes to the filesystem on a disk? For systems software and mission critical programs, it is a better or must-to-do practice to check the available filesystem space before actually writing to files. On POSIX OSes, we have the statvfs POSIX API to get filesystem statistics (On Linux, you may use the Linux specific statfs, but POSIX APIs are better for portability). In this post, we will introduce a C function and a C++ example to use the statvfs API to get the available filesystem space.

The header that you need to include in your C or C++ programs to use the statvfs API:

// header for statvfs
#include <sys/statvfs.h>

and the prototype of the statvfs is

int statvfs(const char *path, struct statvfs *buf);

The results will be filled to the buf statvfs struct:

struct statvfs {
    unsigned long  f_bsize;    /* filesystem block size */
    unsigned long  f_frsize;   /* fragment size */
    fsblkcnt_t     f_blocks;   /* size of fs in f_frsize units */
    fsblkcnt_t     f_bfree;    /* # free blocks */
    fsblkcnt_t     f_bavail;   /* # free blocks for unprivileged users */
    fsfilcnt_t     f_files;    /* # inodes */
    fsfilcnt_t     f_ffree;    /* # free inodes */
    fsfilcnt_t     f_favail;   /* # free inodes for unprivileged users */
    unsigned long  f_fsid;     /* filesystem ID */
    unsigned long  f_flag;     /* mount flags */
    unsigned long  f_namemax;  /* maximum filename length */
};

For unprivileged users, there are f_bavail available blocks in the filesystem and each block’s size is f_bsize bytes. So the overall available space in the filesystems is

f_bsize * f_bavail

I summarize and implement the method here in one simple function as follows.

long GetAvailableSpace(const char* path)
{
  struct statvfs stat;

  if (statvfs(path, &stat) != 0) {
    // error happens, just quits here
    return -1;
  }

  // the available size is f_bsize * f_bavail
  return stat.f_bsize * stat.f_bavail;
}

If you are using boost in your C++ project, you may alternatively use the space function.

With the above GetAvailableSpace function, a full example in C++ is as follows.

The program can accept a path to a file or a directory and report the available space in the corresponding filesystem. Several examples are as follows. Here, the above C++ program is build to GetAvailableSpace.

Find the available space where a file is in:

$ touch /tmp/a.txt
$ ./GetAvailableSpace /tmp/a.txt 
Available space under `/tmp/a.txt`: 4140032000 bytes.

Find the available space from a directory path (no need to be a mount point):

$ ./GetAvailableSpace /tmp/
Available space under `/tmp/`: 4140032000 bytes.

Note that the directory must exist. Otherwise, it will reports an error:

$ ./GetAvailableSpace /dd/
Available space under `/dd/`: 
ERROR: failed to get available space

Similar Posts

  • Friendly WordPress Navigation Using Page Numbers Instead of Next and Previous Links

    The navigation will be more user friendly with page numbers instead of next and previous links since users can navigate much quicker to the page they want to see especially when there are a lot of pages. It is also good method for SEO (Search Engine Optimization) because it creates a tighter inner link structure….

  • rtl8192cu driver for CentOS 7

    I find the rtl8192cu wireless adapter driver on CentOS 7 is quite unstable. After running a while, the connection will disappear. How to make it stable? There is a bug in some hardware where the device never wakes back up. You may try disabling the power management by putting a file 8192cu-disable-power-management.conf under /etc/modprobe.d/: #…

  • Crypto Futures vs. Perpetuals: Key Differences Explained

    In the dynamic world of cryptocurrency trading, “futures” and “perpetuals” are two of the most popular instruments for speculators and hedgers. While often discussed together, they are distinct products with crucial differences. Both allow traders to bet on the future price of a cryptocurrency without actually owning it. [1][2] What are Crypto Futures? A crypto…

  • Micosoft招聘部分算法题

    Micosoft招聘部分算法题 1.链表和数组的区别在哪里? 2.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法? 3.编写实现数组排序的一种算法。说明为什么你会选择用这样的方法? 4.请编写能直接实现strstr()函数功能的代码。 5.编写反转字符串的程序,要求优化速度、优化空间。 6.在链表里如何发现循环链接? 7.给出洗牌的一个算法,并将洗好的牌存储在一个整形数组里。 8.写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?) 9.给出一个函数来输出一个字符串的所有排列。 10.请编写实现malloc()内存分配函数功能一样的代码。 11.给出一个函数来复制两个字符串A和B。字符串A的后几个字节和字符串B的前几个字节重叠。 12.怎样编写一个程序,把一个有序整数数组放到二叉树中? 13.怎样从顶部开始逐层打印二叉树结点数据?请编程。 14.怎样把一个链表掉个顺序(也就是反序,注意链表的边界条件并考虑空链表)? 来源:·日月光华 bbs.fudan.edu.cn Read more: Java Calling Native Functions in .DLL on Windows OCaml Learning Materials Online Tutorials for Linux Beginners How to Run a Command Upon Files or Directories Changes on Linux Parameterised AngularJS Routing in Asp.net MVC using $routeProvider…

  • How to install the MATE fork of Gnome 2 on Fedora 17?

    I miss Gnome 2. How to install the MATE fork of Gnome 2 on Fedora 17? MATE is already included into Fedora 17’s repository and is an official feature of Fedora 18. To install MATE on Fedora 17 # yum install @mate-desktop To install softwares usually needed: # yum install mate-media mate-screensaver mate-system-monitor mate-power-manager mate-utils…

Leave a Reply

Your email address will not be published. Required fields are marked *