File: magic.c

package info (click to toggle)
zgv 3.0-4
  • links: PTS
  • area: main
  • in suites: slink
  • size: 680 kB
  • ctags: 616
  • sloc: ansic: 6,696; makefile: 109; sh: 23
file content (83 lines) | stat: -rw-r--r-- 1,906 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* Zgv v2.8 - GIF, JPEG and PBM/PGM/PPM viewer, for VGA PCs running Linux.
 * Copyright (C) 1993-1996 Russell Marks. See README for license details.
 *
 * magic.c - Determines type of image file.
 */

#include <stdio.h>
#include <string.h>
#include "magic.h"


int magic_ident(char *filename)
{
FILE *in;
unsigned char buf[3];

if((in=fopen(filename,"rb"))==NULL)
  return(_IS_BAD);

buf[0]=buf[1]=buf[2]=0;
fread(buf,1,3,in);
fclose(in);

/* We use the following rules:
 * P?M files must have 'P', then a digit; '1'<=digit<='6'.
 * GIF files must have "GIF"
 * JPEG files must have first byte=0xff, second byte=0xd8 (M_SOI)
 * BMP files must start with "BM"
 * PCX files have 0x0A, version byte, then 0x01.
 * mrf files must have "MRF"
 * TGA files suck rocks ;-) (heuristics in this case)
 */

/* no magic for technical reasons - test for '.ngm' extension */
if(strlen(filename)>=4 && !strcasecmp(filename+strlen(filename)-4,".ngm"))
  return(_IS_NGM);

/* xvpics look a bit like P?M files */
if(!strncmp(buf,"P7 ",3))
  return(_IS_XVPIC);

/* PBM/PGM/PPM */
if(buf[0]=='P' && buf[1]>='1' && buf[1]<='6')
  return(_IS_PNM);

/* GIF */
if(strncmp(buf,"GIF",3)==0)
  return(_IS_GIF);

/* JPEG */
if(buf[0]==0xff && buf[1]==0xd8)
  return(_IS_JPEG);

/* BMP */
if(buf[0]=='B' && buf[1]=='M')
  return(_IS_BMP);

#ifdef PNG_SUPPORT
/* PNG */
if(buf[0]==0x89 && buf[1]=='P' && buf[2]=='N')
  return(_IS_PNG);		/* XXX should test the rest I s'pose */
#endif

/* PCX */
if(buf[0]==10 && buf[2]==1)
  return(_IS_PCX);

/* mrf */
if(strncmp(buf,"MRF",3)==0)
  return(_IS_MRF);

/* TGA */
/* this is hairy, since TGA files don't have a magic number.
 * we make a guess based on some of the image info.
 * (whether it has a colourmap or not, and the type)
 */
if((buf[1]==1 && (buf[2]==1 || buf[2]==9)) ||
   (buf[1]<=1 && (buf[2]==2 || buf[2]==10)))
  return(_IS_TGA);

/* if no valid header */
return(_IS_BAD);
}