开发者

An efficient way to print a string to a file

I have a

char* aString

and I want 开发者_Go百科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?


fwrite

http://www.cplusplus.com/reference/clibrary/cstdio/fwrite/


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜