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?
-
2Can you post some sample code showing us what is the input and what is the expected output?Naveen– Naveen2010-01-07 07:01:18 +00:00Commented Jan 7, 2010 at 7:01
-
I have something like this: ... string St1, St2; ... ifstream In("Text.txt"); In >> St1 >> St2; ... that St1 and St2 are initialized by reading from a file by ifstream() function. Now I want to write them in another file by fprintf() function. fprintf("%s %s", St1, St2); But I think fprint get char* not string.aryan– aryan2010-01-07 08:06:04 +00:00Commented Jan 7, 2010 at 8:06
-
The first argument for fprintf should be a FILE*, not a char *. In C there's no "string", only "char *". Are you sure you didn't mean to tag this question with "c++" rather than "c" ?Remo.D– Remo.D2010-01-07 16:38:51 +00:00Commented Jan 7, 2010 at 16:38
Add a comment
|
3 Answers
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());
Comments
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);
1 Comment
aryan
I have something like this: ... string St1, St2; ... ifstream In("Text.txt"); In >> St1 >> St2; ... that St1 and St2 are initialized by reading from a file by ifstream() function. Now I want to write them in another file by fprintf() function. fprintf("%s %s", St1, St2); But I think fprint get char* not string.