Advertisement
STANAANDREY

read bmp dimension

Jan 12th, 2023
756
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdint.h>
  5. #include <assert.h>
  6. #define EXPECT_EXT "bmp"
  7. #define WIDTH_OFFSET 0x12
  8. #define HEIGHT_OFFSET 0x16
  9.  
  10. void checkArgs(int argc, char *argv[]) {
  11.   if (argc == 1) {
  12.     fprintf(stderr, "one more arg needed!\n");
  13.     exit(-1);
  14.   }
  15.   char *ext = strrchr(argv[1], '.') + 1;
  16.   if (strcmp(ext, EXPECT_EXT) != 0) {
  17.       fprintf(stderr, "wrong extension, expected: %s, found: %s\n", EXPECT_EXT, ext);
  18.       exit(-1);
  19.   }
  20. }
  21.  
  22. FILE *safeOpenFile(const char path[], const char mode[]) {
  23.   FILE *file = NULL;
  24.   if ((file = fopen(path, mode)) == NULL) {
  25.     perror("");
  26.     exit(EXIT_FAILURE);
  27.   }
  28.   return file;
  29. }
  30.  
  31. void safeCloseFile(FILE *file) {
  32.   if (fclose(file) == EOF) {
  33.     perror("");
  34.     exit(EXIT_FAILURE);
  35.   }
  36. }
  37.  
  38. uint32_t read(FILE *file, long offset) {
  39.   fseek(file, offset, SEEK_SET);
  40.   uint32_t data;
  41.   assert(fread(&data, sizeof(uint32_t), 1, file) == 1);
  42.   return data;
  43. }
  44.  
  45. int main(int argc, char *argv[]) {
  46.   checkArgs(argc, argv);
  47.   FILE *file = safeOpenFile(argv[1], "rb");
  48.  
  49.   int width = read(file, WIDTH_OFFSET);
  50.   int height = read(file, HEIGHT_OFFSET);
  51.   printf("dimension: %u X %u\n", width, height);
  52.  
  53.   safeCloseFile(file);
  54.   return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement