I have a small 50MiB partition formatted as ext4 with only one directory that contains a set of photos mounted on / mnt / tmp.
Then I use statvfs() to calculate the bytes used in the section and lstat() to calculate the size of each file inside, for this I wrote this program:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <sys/statvfs.h> #include <stdint.h> #include <string.h> #include <dirent.h> #include <stdlib.h> //The amount of bytes of all files found uint64_t totalFilesSize=0; //Size for a sector in the fs unsigned int sectorSize=0; void readDir(char *path) { DIR *directory; struct dirent *d_file; // a file in *directory directory = opendir (path); while ((d_file = readdir (directory)) != 0) { struct stat filestat; char *abPath=malloc(1024); memset(abPath, 0, 1024); strcpy(abPath, path); strcat(abPath, "/"); strcat(abPath, d_file->d_name); lstat (abPath, &filestat); switch (filestat.st_mode & S_IFMT) { case S_IFDIR: { if (strcmp (".", d_file->d_name) && strcmp ("..", d_file->d_name)) { printf("File: %s\nSize: %d\n\n", abPath, filestat.st_size); //Add slack space to the final sum int slack=sectorSize-(filestat.st_size%sectorSize); totalFilesSize+=filestat.st_size+slack; readDir(abPath); } break; } case S_IFREG: { printf("File: %s\nSize: %d\n\n", abPath, filestat.st_size); //Add slack space to the final sum int slack=sectorSize-(filestat.st_size%sectorSize); totalFilesSize+=filestat.st_size+slack; break; } } free(abPath); } closedir (directory); } int main (int argc, char **argv) { if(argc!=2) { printf("Error: Missing required parameter.\n"); return -1; } struct statvfs info; statvfs (argv[1], &info); sectorSize=info.f_bsize; //Setting global variable uint64_t usedBytes=(info.f_blocks-info.f_bfree)*info.f_bsize; readDir(argv[1]); printf("Total blocks: %d\nFree blocks: %d\nSize of block: %d\n\ Size in bytes: %d\nTotal Files size: %d\n", info.f_blocks, info.f_bfree, info.f_bsize, usedBytes, totalFilesSize); return 0; }
Passing the mount point of the partition as a parameter (/ mnt / tmp), the program displays this output:
File: /mnt/tmp/lost+found Size: 12288 File: /mnt/tmp/photos Size: 1024 File: /mnt/tmp/photos/IMG_3195.JPG Size: 2373510 File: /mnt/tmp/photos/IMG_3200.JPG Size: 2313695 File: /mnt/tmp/photos/IMG_3199.JPG Size: 2484189 File: /mnt/tmp/photos/IMG_3203.JPG Size: 2494687 File: /mnt/tmp/photos/IMG_3197.JPG Size: 2259056 File: /mnt/tmp/photos/IMG_3201.JPG Size: 2505596 File: /mnt/tmp/photos/IMG_3202.JPG Size: 2306304 File: /mnt/tmp/photos/IMG_3204.JPG Size: 2173883 File: /mnt/tmp/photos/IMG_3198.JPG Size: 2390122 File: /mnt/tmp/photos/IMG_3196.JPG Size: 2469315 Total blocks: 47249 Free blocks: 19160 Size of block: 1024 Size in bytes: 28763136 Total Files size: 23790592
Pay attention to the last two lines. In the FAT32 file system, the sum is the same, but in ext4 it is different.
So the question is: why?
source share