13 /* Print Magic Error */
16 /* very stupid aproach, but very simple :) */
17 struct association_s
{
18 const char *filetype
; /* filetype of the file */
19 const char *viewapp
; /* path to the view program */
20 const char *editapp
; /* path to the edit program */
25 int entry_count
= sizeof(associations
)/sizeof(struct association_s
);
27 /* determine <file> filetype
29 * if successfull <filetype> must be freed later by the user
30 * returns true if successfull, false otherwise
33 bool getfiletype(char *file
, char **filetype
)
35 assert (file
!= NULL
);
37 magic_t mc
; //magic_cookie
42 stat
= access(file
, F_OK
);
48 mc
= magic_open(MAGIC_NONE
);
54 stat
= magic_load(mc
, NULL
);
56 fprintf(stderr
, "AH: %s", magic_error(mc
));
60 magictype
= magic_file(mc
, file
);
61 if (magictype
== NULL
) {
62 fprintf(stderr
, "AH: %s", magic_error(mc
));
65 //printf("Magic says: %s\n\n", magictype);
67 /* "convert" (or copy) magic result to something local to close magic */
68 magictypelen
= strlen(magictype
);
69 (*filetype
) = (char *)malloc(magictypelen
+1);
70 if (*filetype
== NULL
) {
74 strncpy(*filetype
, magictype
, magictypelen
+1);
82 /* match <filetype> against local database
84 * <index> gets the index of the found entry, if successfull
85 * returns true if entry was found, false otherwise
87 bool match(char *filetype
, int *index
)
89 assert(filetype
!= NULL
);
90 assert(index
!= NULL
);
96 /* this is a nasty piece of code. need to beautify!!! */
97 for(r
=0, found
=false; (r
< entry_count
) && (found
== false); ++r
) {
98 if (regcomp(&preg
, associations
[r
].filetype
, REG_EXTENDED
| REG_NOSUB
) != 0) {
99 fprintf(stderr
, "Unable to compile regex %s.\n", associations
[r
].filetype
);
102 /* true on substring match. to match whole string prepend with '^' and append '$'. */
103 if (regexec(&preg
, filetype
, 0, 0, 0) == 0) {
114 void main (int argc
, char *argv
[])
123 fprintf(stderr
, "%s: Incorrect arguments.\n", argv
[0]);
124 fprintf(stdout
, "Usage: %s v|e <file>\n", argv
[0]);
125 fprintf(stdout
, "\t v: opens file with application registered to view\n");
126 fprintf(stdout
, "\t e: opens file with application registered to edit\n");
132 stat
= getfiletype(file
, &filetype
);
134 fprintf(stderr
, "Could not determine %s type.\n", file
);
138 stat
= match(filetype
, &index
);
140 fprintf(stderr
, "Type '%s' not configured.\nAdd it to associations "\
141 "array in config.h and recompile.\n", filetype
);
149 newargv
[0] = associations
[index
].editapp
;
151 newargv
[2] = (char *)NULL
;
152 stat
= execv(associations
[index
].editapp
, newargv
);
156 newargv
[0] = associations
[index
].viewapp
;
158 newargv
[2] = (char *)NULL
;
159 stat
= execv(associations
[index
].viewapp
, newargv
);
163 fprintf(stderr
, "No application associated with the action %s for\
164 file %s.\n", argv
[1], file
);