Created
December 2, 2020 05:52
-
-
Save Theldus/f22faa49ce73456fc5e7fc8befd8f1aa to your computer and use it in GitHub Desktop.
'fdisk-like' tool tha lists all the 4 partitions in the MBR scheme for a given file/device
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Public domain, do whatever you want with this. | |
| * | |
| * Build: gcc disksize.c -o disksize -std=c99 -pedantic -Wall -Wextra | |
| * Usage: ./disksize /dev/sdX | |
| */ | |
| #include <stdio.h> | |
| #include <inttypes.h> | |
| #include <assert.h> | |
| #define GiB (1024*1024*1024) | |
| struct partition_table_entry | |
| { | |
| uint8_t status; | |
| uint8_t chs_addr_first_sector[3]; | |
| uint8_t type; | |
| uint8_t chs_addr_last_sector[3]; | |
| uint32_t lba_address; | |
| uint32_t num_sectors; | |
| } __attribute__((packed)); | |
| struct mbr | |
| { | |
| uint8_t trash[446]; | |
| struct partition_table_entry pte[4]; | |
| uint16_t boot_sig; | |
| } __attribute__((packed)); | |
| static char *get_partition_type(int id) | |
| { | |
| switch (id) | |
| { | |
| default: | |
| return "unknown"; | |
| break; | |
| case 0x7: | |
| return "NTFS"; | |
| break; | |
| case 0xB: | |
| case 0xC: | |
| return "FAT32"; | |
| break; | |
| case 0x82: | |
| return "Linux swap"; | |
| break; | |
| case 0x83: | |
| return "Linux"; | |
| break; | |
| } | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| struct mbr mbr; | |
| if (argc < 2) | |
| return (-1); | |
| FILE *f = fopen(argv[1], "r"); | |
| assert(f != NULL); | |
| assert(fread(&mbr, sizeof(mbr), 1, f) == 1); | |
| for (int i = 0; i < 4; i++) | |
| { | |
| printf("Partition #%d info:\n", i); | |
| printf("\tActive: %d \n" , mbr.pte[i].status != 0); | |
| printf("\tNum sectors: %d \n" , mbr.pte[i].num_sectors); | |
| printf("\tPartition type: 0x%x (%s)\n" , | |
| mbr.pte[i].type, get_partition_type(mbr.pte[i].type)); | |
| printf("\tPartition size: %.2f (GiB)\n", | |
| ((double)(mbr.pte[i].num_sectors * 512ULL))/GiB); | |
| } | |
| fclose(f); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment