From 519de783b6681672541c0ac003d959153c5c5904 Mon Sep 17 00:00:00 2001 From: Florian Obser Date: Sat, 5 Dec 2020 16:47:33 +0100 Subject: [PATCH] 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. --- mimes.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/mimes.c b/mimes.c index dd80b7a..4645aca 100644 --- a/mimes.c +++ b/mimes.c @@ -4,13 +4,10 @@ #include "mimes.h" -struct mimes { - char extension[10]; - char type [70]; -}; - - -struct mimes database[] = { +static const struct { + const char *extension; + const char *type; +} database[] = { {"7z", "application/x-7z-compressed"}, {"atom", "application/atom+xml"}, {"avi", "video/x-msvideo"}, @@ -116,15 +113,20 @@ struct mimes database[] = { {"zip", "application/zip"} }; +#ifndef nitems +#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0])) +#endif + void get_file_mime(const char *path, char *type, const ssize_t type_size) { - char *extension; + int i; + char *extension; extension = strrchr(path, '.'); /* 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) { strlcpy(type, database[i].type, type_size); break;