I just start learning C the hard way and i am new to this forum and i hope to
get some advice or if i 'm the right direction.
this the main.c file
Code:
#include <stdio.h>
#include <stdlib.h>
#include <byteswap.h>
#include <stdint.h>
#include "jpeg.h"
enum types {
PDF,
JPEG,
PNG,
GIF,
INVALID
};
typedef enum types format;
format checkFormat(FILE *fd, const uint8_t buffer[]){
if( fd == NULL){
printf("Invalid file format");
}
switch (buffer[0]){
case 0x25:
printf(" PDF \n");
return PDF;
case 0x89:
printf(" PNG \n");
return PNG;
case 0x47:
printf(" GIF \n");
return GIF;
case 0xFF:
printf(" JPEG \n");
return JPEG;
default:
return INVALID;
}
}
int main(int argc, char *argv[]) {
FILE *fd;
long fdSize;
uint8_t *buffer;
printf("Enter file path:");
fd = fopen(argv[1], "rb");
if ( fd == NULL )
{
perror("Unable to open the file");
exit(EXIT_FAILURE);
}
fseek(fd, 0L, SEEK_END);
fdSize = ftell(fd);
/* reset the file position indicator to the beginning of the file */
fseek(fd, 0L, SEEK_SET);
buffer = (uint8_t*)calloc((size_t) fdSize, sizeof(uint8_t));
/* memory error */
if(buffer == NULL)
return 1;
/* copy all the text into the buffer */
fread(buffer, sizeof(uint8_t), (size_t) fdSize, fd);
fclose(fd);
/* fm for later use*/
format fm = checkFormat(fd, (const uint8_t *) buffer);
parseHeader(buffer);
free(buffer);
return 0;
}
jpeg.h file
Code:
#include <stdint.h>
#ifndef FILE_DECODER_JPEG_H
#define FILE_DECODER_JPEG_H
#endif //FILE_DECODER_JPEG_H
typedef struct JHeader {
uint16_t SIO;
uint16_t APP0;
uint16_t Lenght;
uint32_t ID;
uint16_t VERSION;
uint16_t Xdensity;
uint16_t Ydensity;
uint16_t XThumbnail;
uint16_t YThumbnail;
}JHeader;
JHeader parseHeader(uint8_t *buffer);
uint32_t slice(int start, int end, uint8_t *buffer);
jpeg.c file
Code:
#include <stdio.h>
#include <memory.h>
#include <stdint.h>
#include <byteswap.h>
#include "jpeg.h"
JHeader header;
uint32_t slice(int start, int end, uint8_t *buffer){
uint32_t a;
unsigned int i = 0;
uint8_t sl[16];
while(start <= end){
sl[i] = buffer[start];
start++;
i++;
}
memcpy(&a, sl, sizeof(unsigned int));
return a;
}
JHeader parseHeader(uint8_t *buffer) {
header.SIO = bswap_16(slice(0,2, buffer));
header.APP0 = bswap_16(slice(2,3, buffer));
header.Lenght = bswap_16(slice(4,5, buffer));
header.ID = bswap_32(slice(6,9, buffer));
header.VERSION = bswap_16(slice(11,13, buffer));
header.Xdensity = bswap_16(slice(14,15, buffer));
header.Ydensity = bswap_16(slice(16,17, buffer));
header.XThumbnail = buffer[18];
header.YThumbnail = buffer[19];
printf("start of image %x\n", header.SIO);
printf("APP0 marker %x\n", header.APP0);
printf("Length %x\n", header.Lenght);
printf("Identifier %x\n", header.ID);
printf("Version %x\n", header.VERSION);
printf("X density %x\n", header.Xdensity);
printf("Y density %x\n", header.Ydensity);
printf("X thumbnail %x\n", header.XThumbnail);
printf("Y thumbnail %x\n", header.YThumbnail);
return header;
}