Example code, treats argv[1]
as a file path, replacing its extension with .png
or appending it if none is found:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
if (argc != 2)
return 1;
char *lastdot = strrchr(argv[1], '.');
size_t len = lastdot ? (lastdot - argv[1]) : strlen(argv[1]);
char outpath[len + sizeof(".png")];
// ^ this is the important part
memcpy(outpath, argv[1], len);
memcpy(outpath + len, ".png", sizeof(".png"));
printf("%s\n", outpath);
}
My main concern here is that argv[1]
may be just small enough to not cause an error from the OS itself, but then the extra 4 bytes added by the ".png"
concatenation will cause a stack overflow when allocating the VLA?
The problem is that I'm not really sure how the sizes of either a member of argv
or a VLA are limited.
Apparently constants such as PATH_MAX
aren't to be trusted for static array sizes, so it's either this or malloc
.