tags:

views:

76

answers:

3

Hi

I have a

char* aString

and I want to write the portion of aString between from and to, what is the most efficient way?

I think of a way which writes 1 characters at a time.

char* p = aString + from;
for (int i =0; i < (to-from); i++) {
    fprintf(aFile, "%c", p++);
}

I wonder if there is a faster way?

+6  A: 

Don is right that fwrite is the quickest.

That said, here's a little know feature of printf (and snprintf, vprintf, etc.) that allows you to do it in one call.

printf("%.*s", to - from, aString + from);

How this works. Providing a precision for a string says print no more then that many characters (it can print less if it finds a '\0' first). So a line like:

printf("%.5s", "0123456789");

will print:

01234

Next, if you need to specify your precision at runtime, replacing the number with a * and provide the length as a function parameter before the string:

printf("%.*s", 5, "0123456789");  // same as before

If all you want to do is print the one part of the string this trick is overkill. But in combination with other formatting, it can be quite helpful:

printf("Token %d: \"%.*s\"\n",
       tok,
       token_info[tok].len,
       str + token_info[tok].start);
R Samuel Klatchko
I doubt this technique. In my experience, printf() does not truncate arguments in this situation. The man page says: "In no case does a non-existent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result" (from http://linux.die.net/man/3/printf).
unwind
@unwind: You're reading the wrong section. It's the *precision* that's being specified, not the the field width, and the precision has special behavior for `%s`.
jamesdlin
@unwind - as jamesdlin correctly states, you are referring to the field width while I was describing the precision. When specifying just the field width no period is used; when specifying both field width and precision, the field width comes before the period while the precision comes after.
R Samuel Klatchko
+2  A: 

You can use fwrite as follows:

char *s = "abcdef";

fwrite(s,sizeof(char),2,stdout); // prints ab

fwrite(s+2,sizeof(char),2,stdout); // prints cd

// In general
fwrite(s+from,sizeof(char),to-from,stdout); // print char bet s[from] to s[to]

If you want to write to a file you can replace stdout with the corresponding file pointer.

codaddict