tags:

views:

108

answers:

3

I am not asking how to do file I/O, its just more of a formatting question. I need to write a variable number of characters to a file. For example, lets say I want to print 3 characters. "TO" would print "TO" to a file. "LongString of Characters" would print "Lon" to a file.

How can I do this? (the number of characters is defined in another variable). I know that this is possible fprintf(file,"%10s",string), but that 10 is predefined

+9  A: 

This one corresponds to your example:

fprintf(file, "%*s", 10, string);

but you mentioned a maximum as well, to also limit the number:

fprintf(file, "%*.*s", 10, 10, string);
DigitalRoss
+1 for keeping it simple.
Ashwin
A: 

I believe you need "%*s" and you'll need to pass the length as an integer before the string.

Stephen Nutt
This will print _at least_ that many characters, and will not limit the number of characters printed.
Chris Lutz
+1  A: 

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 truncates the string to the length you want and then restores it. Sure, it's not strictly necessary, but it works, and it's quite easy to understand.

Chris Lutz
If you do this... be sure that the length of `string` is at least `num-1` or you will be temporarily overwriting some random byte of memory!!
jnylen
This is true. Let it be a lesson never to trust hastily/lazily written code you get off the internet.
Chris Lutz