C program to check whether the file is JPEG file or not

Write a C program which inputs a file as a command-line arguments and detects whether the file is JPEG(Joint Photographic Experts Group) or not.


  1. We will give an image as a command line argument while executing the code.
  2. Read the first three bytes of the given image(file).
  3. After reading the file bytes, compare it with the condition for JPEG file i.e., if the first, second, and third byte of the given file is 0xff, 0xd8, and 0xff respectively then the given file is JPEG file.
  4. Else it is not a JPEG File.

Below is the implementation of the above approach:





// C program for the above approach
#include <ctype.h>
#include <stdio.h>
#include <string.h>
// Driver Code
int main(int argc, char* argv[])
    // If number of command line
    // argument is not 2 then return
    if (argc != 2) {
        return 1;
    // Take file as argument as an
    // input and read the file
    FILE* file = fopen(argv[1], "r");
    // If file is NULL return
    if (file == NULL) {
        return 1;
    // Array to store the char bytes
    unsigned char bytes[3];
    // Read the file bytes
    fread(bytes, 3, 1, file);
    // Condition for JPEG image
    // If the given file is a JPEG file
    if (bytes[0] == 0xff
        && bytes[1] == 0xd8
        && bytes[1] == 0xff) {
        printf("This Image is "
               "in JPEG format!");
    // Else print "No"
    else {
    return 0;



My Personal Notes arrow_drop_up

Check this out nerdboinet

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.