Last active
November 4, 2022 14:38
-
-
Save weiss/9253515ad10343f14d4c71439c0893e0 to your computer and use it in GitHub Desktop.
Read farbfeld image into struct
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
#include <err.h> | |
#include <inttypes.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <arpa/inet.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
struct __attribute__((__packed__)) ff_img_s { | |
unsigned char magic[8]; | |
uint32_t width; | |
uint32_t height; | |
unsigned char data[]; | |
}; | |
int | |
main(int argc, char **argv) | |
{ | |
struct stat s; | |
struct ff_img_s *img; | |
FILE *f; | |
if (argc != 2) | |
errx(EXIT_FAILURE, "Usage: ff <file>"); | |
if (stat(argv[1], &s) != 0) | |
err(EXIT_FAILURE, "Cannot stat %s", argv[1]); | |
if (s.st_size < 16) | |
errx(EXIT_FAILURE, "%s is too small", argv[1]); | |
if ((img = malloc(s.st_size)) == NULL) | |
err(EXIT_FAILURE, "Cannot allocate memory for reading %s", argv[1]); | |
if ((f = fopen(argv[1], "r")) == NULL) | |
err(EXIT_FAILURE, "Cannot open %s", argv[1]); | |
if (fread(img, 1, s.st_size, f) != (size_t)s.st_size) | |
err(EXIT_FAILURE, "Cannot read %s", argv[1]); | |
if (fclose(f) != 0) | |
err(EXIT_FAILURE, "Cannot close %s", argv[1]); | |
if (memcmp(img->magic, "farbfeld", sizeof("farbfeld") - 1) != 0) | |
errx(EXIT_FAILURE, "%s is not a farbfeld image", argv[1]); | |
(void)printf("W: %"PRIu32"\n", ntohl(img->width)); | |
(void)printf("H: %"PRIu32"\n", ntohl(img->height)); | |
free(img); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment