Taking your last question first, ensuring a maximum size is pretty easy. Typically you want to use fgets
to read the string. This allows you to specify a maximum length. Alternatively, you can specify a maximum size in a scanf format (e.g., "%29s"
or "%29[^\n]"
). Note the difference between the two: with fgets
you specify the buffer size, but with scanf
you specify one less than the buffer size (i.e., the maximum number of characters to read).
As for the first question: yes, there are generally better ways. strncpy
is a strange function, originally written for a fairly specific purpose, and (to be honest) should probably be removed from the standard library, because while it seems like it should be useful, it almost never really is.
I'd probably do things a little differently. One possibility would be to use snprintf
, something like:
snprintf(
out_file_name,
sizeof(out_file_name),
"%*s",
strlen(FileName) - strlen(IN_FILE_SUFFIX), FileName);