Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

Approach:

  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 {
  
        printf("No");
    }
  
    return 0;
}

Output:


My Personal Notes arrow_drop_up
Last Updated : 08 Jun, 2020
Like Article
Save Article
Similar Reads