[ACCEPTED]-How do I set the number of characters output in a fprintf '%s' format using a variable?-printf
Accepted answer
This one corresponds to your example:
fprintf(file, "%*s", 10, string);
but 2 you mentioned a maximum as well, to also 1 limit the number:
fprintf(file, "%*.*s", 10, 10, string);
I believe you need "%*s" and you'll need 2 to pass the length as an integer before 1 the string.
As an alternative, why not try this:
void print_limit(char *string, size_t num)
{
char c = string[num];
string[num] = 0;
fputs(string, file);
string[num] = c;
}
Temporarily 4 truncates the string to the length you want 3 and then restores it. Sure, it's not strictly 2 necessary, but it works, and it's quite 1 easy to understand.
As an alternative, you may create "c_str" from 4 your buffer and prepare string to printf 3 like I do that in this source:
void print(char *val, size_t size) {
char *p = (char *)malloc(size+1); // +1 to zero char
char current;
for (int i=0; i < size; ++i) {
current = val[i];
if (current != '\0') {
p[i] = current;
} else {
p[i] = '.'; // keep in mind that \0 was replace by dot
}
p[i+1] = '\0';
}
printf("%s", p);
free(p);
}
But it solution 2 wrong way. You shuld use fprintf with format 1 "%*s".
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.