char out_file_name[30];
ogSize = strlen(FileName); //i.e. - FileName_anylength.log (always.log)
ogSize -= strlen(IN_FILE_SUFFIX); //amount of chars before .log
strncpy( out_file_name, FileName, ogSize ); //out_file_name now is FileName_anylength (without the .log)
Is this the best way to do this?
Also, how do I guard that ogSize doesn't happen to be more than 30 chars as it is coming from user input?
Thank You.
Another way to truncate a String is to use the split() method, which uses a regular expression to split the String into pieces. The first element of results will either be our truncated String, or the original String if length was longer than text.
Make a loop at the end of the string After cutting the string at the proper length, take the end of the string and tie a knot at the very end, then fold the string over and tie a loop, about the same size as the original loop (about 2cm in diameter).
SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.
Truncation in IT refers to “cutting” something, or removing parts of it to make it shorter. In general, truncation takes a certain object such as a number or text string and reduces it in some way, which makes it less resources to store.
With a C-style string, you can just set the character you want to truncate on to \0
.
Regarding your second question, basically you check. Or you allocate as much memory as you need, based on the string size (remember to include room for that \0
).
Give this a look:
char *trunc;
char *outfile;
strdup( outfile, FileName );
if ( ((trunc = strstr( out_file_name, ".log" )) != NULL )
*trunc = '\0';
return ( outfile ); // assumes returning result from function
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With