I am writing a c++ program that I need to get partitions and hhd's total, free and used space.
I'm so confused with all commands and codes that can be used to get these data from system and all differences between outputs.
I read this link : Why are there so many different ways to measure disk usage? , that was useful, but didn't really helped me to solve my problem
I understood that reason of difference in sizes between output of lsblk
and df
is that df
gives file system's size and lsblk
gives partition's size. the thing that I need is also partition's size
. but as far as I know, lsblk
only gives total size of partiton.(am I right?)
I also used statvfs
structure in my code and outputs were so close to df's output.
so what am I supposed to use to get exact free, used and total size of partition and hdds?
Asked
Active
Viewed 1,716 times
0

fa7eme
- 43
1 Answers
1
On the command line, you could use:
lsblk -bo NAME,SIZE,FSTYPE,FSSIZE,FSUSED,FSAVAIL,FSUSE%
But in a c++ program, you generally don't want to parse the output of any other commands: you should use system and library calls to get the information directly.
Finding the right calls for the job is more Stack Overflow territory, but here are a few pointers:
- file system capacity/used/free values:
statvfs(2)
orstd::filesystem::space
. - size of a block device: use the
BLKGETSIZE64
ioctl to get the size in bytes, and if you need the size in blocks, also use theBLKSSZGET
ioctl to get the block size, and divide the size in bytes by the size of a single block. Here's another example.

telcoM
- 96,466
-
actually I want to find exact command and see it's source code to know it's way of calculating space. I tested command you mentioned but it didn't have those option like FUSED and.. and about statvfs, as I mentioned, it gives output like df, and df is about file system's total and other things size. about the other code, it doesn't have permission to open /dev/sda. did i do something wrongly? – fa7eme Jul 21 '20 at 08:03
-
The
lsblk
command I suggested works in Debian 10.lsblk --version
sayslsblk from util-linux 2.33.1
. If your distribution has an older version, it might not have all the same options. If it has a newer version, you might want to check its man page and/orlsblk --help
- the syntax may have changed. (And this is why you want to avoid parsing command output.) The source code forlsblk
can be found here. – telcoM Jul 21 '20 at 09:07
It is very hard to give an exact size of free space available for data on a disk, since that depends on how you are going to use the remaining space: for example writing lots of small files versus one big file may result in different proportions of useful data in relation to the total amount used including metadata and internal file system structures. For a start, one file only needs space for a single file name, a million files needs space for a million names.
– Johan Myréen Jul 21 '20 at 07:42