Created
June 1, 2023 10:53
-
-
Save sidsbrmnn/8eaee7fd7a635af8808fa2f428373e45 to your computer and use it in GitHub Desktop.
Test if a given file is JPEG or not in C
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 <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