开发者

fprintf with string argument

开发者 https://www.devze.com 2022-12-15 21:11 出处:网络
In order to create a formatted file, I 开发者_开发知识库want to utilize fprintf. It must get char* parameters, but I have several string variables. How can I use fprintf?The basic usage of fprintf wit

In order to create a formatted file, I 开发者_开发知识库want to utilize fprintf. It must get char* parameters, but I have several string variables. How can I use fprintf?


The basic usage of fprintf with strings looks like this:

char *str1, *str2, *str3;
FILE *f;
// ...

f = fopen("abc.txt", "w");
fprintf(f, "%s, %s\n", str1, str2);
fprintf(f, "more: %s\n", str3);
fclose(f);

You can add several strings by using several %s format specifiers and you can use repeated calls to fprintf to write the file incrementally.

If you have C++ std::string objects you can use their c_str() method to get a const char* suitable to use with fprintf:

std::string str("abc");
fprintf(f, "%s\n", str.c_str());


fprintf with multiple strings is pretty simple, if that is what you are after, e.g.

const char* charString1 = "This";
const char* charString2 = "is a";
const char* charString3 = "test";

fprintf(fileHandle, "%s, %s, %s", charString1, charString2, charString3);


fprintf works analogous to printf, in the format specifier, you can mention as many %s as you want and give the corresponding number of string arguments. If you want a more detailed answer, please post your code.

0

精彩评论

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