c-md/srcs/utils/string/infer_ext_from_filename.c.md
2026-01-12 16:22:13 +01:00

61 lines
1.2 KiB
Markdown

# infer_ext_from_filename.c
Infer file extension from filename ending with .md
---
## Includes
```c
#include <string.h>
#include "utils.h"
```
---
## Function Descriptions
### `infer_ext_from_filename`
Infer the file extension from a filename that ends with `.md`.
#### Parameters
- `path`: Pointer to the filename string.
#### Return Value
Returns a pointer to a static buffer containing the inferred extension, or
`NULL` if no valid
```c
const char *
infer_ext_from_filename(const char *path)
{
static char ext_buffer[32];
const char *md_ext;
const char *before_md;
const char *dot;
size_t len;
size_t ext_len;
if (NULL == path)
return (NULL);
len = strlen(path);
if (len < 6)
return (NULL);
md_ext = path + len - 3;
if (0 != strcmp(md_ext, ".md"))
return (NULL);
before_md = md_ext - 1;
while (before_md > path && '.' != *before_md)
before_md--;
if (before_md == path || '.' != *before_md)
return (NULL);
dot = before_md;
if (dot + 1 >= md_ext)
return (NULL);
ext_len = md_ext - (dot + 1);
if (ext_len >= sizeof(ext_buffer))
return (NULL);
memcpy(ext_buffer, dot + 1, ext_len);
ext_buffer[ext_len] = '\0';
return (ext_buffer);
}
```