Created
November 4, 2022 14:40
-
-
Save weiss/0eab14c12d062a1c2d36ee6706f776bd to your computer and use it in GitHub Desktop.
Read farbfeld image into header array and body buffer
This file contains 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> | |
int | |
main(int argc, char **argv) | |
{ | |
struct stat s; | |
uint32_t header[4]; | |
unsigned char *img; | |
size_t img_size; | |
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 ((size_t)s.st_size < sizeof(header)) | |
errx(EXIT_FAILURE, "%s is too small", argv[1]); | |
img_size = s.st_size - sizeof(header); | |
if ((img = malloc(img_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(header, 1, sizeof(header), f) != sizeof(header)) | |
err(EXIT_FAILURE, "Cannot read header of %s", argv[1]); | |
if (fread(img, 1, img_size, f) != img_size) | |
err(EXIT_FAILURE, "Cannot read image data of %s", argv[1]); | |
if (fclose(f) != 0) | |
err(EXIT_FAILURE, "Cannot close %s", argv[1]); | |
if (memcmp(header, "farbfeld", sizeof("farbfeld") - 1) != 0) | |
errx(EXIT_FAILURE, "%s is not a farbfeld image", argv[1]); | |
(void)printf("W: %"PRIu32"\n", ntohl(header[2])); | |
(void)printf("H: %"PRIu32"\n", ntohl(header[3])); | |
free(img); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment