I recommend using OpenCV for writing images. Generate a file name like this:
std::ostringstream jpg_filename;
jpg_filename << file_path << "frame" << count << ".jpg";
++count;
I guess there should be a variant to create a printf style formatted string too, but I haven't tried anything.
If you are not doing so already, you need to convert your sensor_msgs::Image to cv::Mat format. There is a nice tutorial for that.
And finally save your image.
cv::imwrite(jpg_filename.str(), your_cv_mat);
Make sure to define OpenCV as a dependency and include the right headers:
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
Best
Tim