Skip to content

Instantly share code, notes, and snippets.

@moe91asd
Created May 8, 2024 15:28
Show Gist options
  • Save moe91asd/3e49ba58d96b5c3be44f7fc90cb0b7e6 to your computer and use it in GitHub Desktop.
Save moe91asd/3e49ba58d96b5c3be44f7fc90cb0b7e6 to your computer and use it in GitHub Desktop.
Test if a given file is JPEG or not in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BYTES 3
int
main (const int argc, const char *argv[])
{
if (argc != 2) {
printf("usage: %s [filename]\n", argv[0]);
return EXIT_FAILURE;
}
const char *filename = argv[1];
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
perror("fopen");
printf("error: unable to open the file\n");
return EXIT_FAILURE;
}
char bytes[MAX_BYTES] = {0};
char expected[MAX_BYTES] = {0xFF, 0xD8, 0xFF};
int count = fread(bytes, 1, MAX_BYTES, fp);
if (count != MAX_BYTES) {
printf("error: unable to read the file\n");
return EXIT_FAILURE;
}
if (memcmp(bytes, expected, MAX_BYTES) == 0) {
printf("YES\n");
}
else {
printf("NO\n");
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment