Fprintf with string argument

To create a formatted file, I want to use fprintf . It should get char* parameters, but I have a few string variables. How to use fprintf ?

+6
c string printf
source share
3 answers

The main use of fprintf with strings is as follows:

 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 multiple lines using multiple %s format specifiers, and you can use fprintf repeated calls to gradually create the file.

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

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

multi-line fprintf is pretty simple if that is what you need e.g.

 const char* charString1 = "This"; const char* charString2 = "is a"; const char* charString3 = "test"; fprintf(fileHandle, "%s, %s, %s", charString1, charString2, charString3); 
+3
source share

fprintf works similarly to printf, in the format specifier you can specify as many% s as you want and specify the corresponding number of string arguments. If you want a more detailed answer, send your code.

+1
source share

All Articles