我有一个将 ppm 文件(一种图片格式)写入磁盘的功能。它将文件名作为 char* 数组。在我的主函数中,我使用字符串流和 << 运算符组合了一个文件名。然后,我想将结果传递给我的 ppm 函数。我在其他地方看到过这个讨论,通常使用非常复杂的方法(许多中间转换步骤)。
我所做的显示在下面的代码中,其他人通常在许多步骤中使用临时变量做的棘手部分是(char*) (PPM_file_name.str().data())
. 这样做的目的是使用 .str() 从 stringstream PPM_file_name 中提取字符串,然后使用 .data() 获取指向其实际内容的指针(这是一个 const char*),然后将其转换为常规 (char*)。更完整的例子如下。
到目前为止,我发现以下工作正常,但这让我感到不安,因为通常当其他人以看似更复杂的方式完成某事时,这是因为这是一种更安全的方式。那么,谁能告诉我我在这里所做的是否安全以及它的便携性如何?
谢谢。
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
// String stream to hold the file name so I can create it from a series of other variable
stringstream PPM_file_name;
// ... a bunch of other code where int ccd_num and string cur_id_str are created and initialized
// Assemble the file name
PPM_file_name << "ccd" << ccd_num << "_" << cur_id_str << ".ppm";
// From PPM_file_name, extract its string, then the const char* pointer to that string's data, then cast that to char*
write_ppm((char*)(PPM_file_name.str().data()),"ladybug_vidcapture.cpp",rgb_images[ccd_num],width,height);
return 0;
}