cstringprintf

fprintf with string argument


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?


Solution

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