n179911
n179911

Reputation: 20301

An efficient way to print a string to a file

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?

Upvotes: 1

Views: 958

Answers (3)

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

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);

Upvotes: 6

codaddict
codaddict

Reputation: 454970

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.

Upvotes: 2

Related Questions