I have a function to write ppm files (image format) to disk. It takes the file name as a char * array. In my main function, I compiled a file name using a string stream and an <operator. Then I want to pass the results of this to my ppm function. I saw this discussed elsewhere, often with very confusing methods (many of the transition steps).
What I did is shown in the code below, and the tricky part that others usually take many steps with temporary variables is (char*) (PPM_file_name.str().data()). To do this, extract the string from stringstream PPM_file_name using .str (), and then get a pointer to its actual contents using .data () (this is const char *), and then apply it to the regular (char *). A more complete example is below.
I found the following to work well so far, but it makes me restless, because usually when other people did something seemingly more confusing, this is because it is a safer way to do this. So, can someone tell me that what I'm doing here is safe, and also how portable is it?
Thank.
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
stringstream PPM_file_name;
PPM_file_name << "ccd" << ccd_num << "_" << cur_id_str << ".ppm";
write_ppm((char*)(PPM_file_name.str().data()),"ladybug_vidcapture.cpp",rgb_images[ccd_num],width,height);
return 0;
}