Declare and initialize the mime database in one statement.
This way the compiler can figure out the correct sizing of the strings for us and we won't forget to increase the char arrays if a longer mime type gets declared. While here introduce nitems macro to simplify for loop.
This commit is contained in:
parent
da225e1adc
commit
519de783b6
20
mimes.c
20
mimes.c
|
@ -4,13 +4,10 @@
|
||||||
|
|
||||||
#include "mimes.h"
|
#include "mimes.h"
|
||||||
|
|
||||||
struct mimes {
|
static const struct {
|
||||||
char extension[10];
|
const char *extension;
|
||||||
char type [70];
|
const char *type;
|
||||||
};
|
} database[] = {
|
||||||
|
|
||||||
|
|
||||||
struct mimes database[] = {
|
|
||||||
{"7z", "application/x-7z-compressed"},
|
{"7z", "application/x-7z-compressed"},
|
||||||
{"atom", "application/atom+xml"},
|
{"atom", "application/atom+xml"},
|
||||||
{"avi", "video/x-msvideo"},
|
{"avi", "video/x-msvideo"},
|
||||||
|
@ -116,15 +113,20 @@ struct mimes database[] = {
|
||||||
{"zip", "application/zip"}
|
{"zip", "application/zip"}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#ifndef nitems
|
||||||
|
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
|
||||||
|
#endif
|
||||||
|
|
||||||
void
|
void
|
||||||
get_file_mime(const char *path, char *type, const ssize_t type_size)
|
get_file_mime(const char *path, char *type, const ssize_t type_size)
|
||||||
{
|
{
|
||||||
char *extension;
|
int i;
|
||||||
|
char *extension;
|
||||||
|
|
||||||
extension = strrchr(path, '.');
|
extension = strrchr(path, '.');
|
||||||
|
|
||||||
/* look for the MIME in the database */
|
/* look for the MIME in the database */
|
||||||
for (int i = 0; i < sizeof(database) / sizeof(struct mimes); i++) {
|
for (i = 0; i < nitems(database); i++) {
|
||||||
if (strcmp(database[i].extension, extension + 1) == 0) {
|
if (strcmp(database[i].extension, extension + 1) == 0) {
|
||||||
strlcpy(type, database[i].type, type_size);
|
strlcpy(type, database[i].type, type_size);
|
||||||
break;
|
break;
|
||||||
|
|
Loading…
Reference in New Issue