修改结构指针中的C字符串

时间:2014-09-28 06:00:09

标签: c++ c string pointers struct

我的代码看起来像这样:

typedef struct
{
  char mode;       //e = encrypt, d = decrypt
  char* infile;    //name of infile
  char* outfile;   //name of outfile
  char* password;  //password string
} cipher_t;

int check_files(cipher_t *data)
{
  char temp_path[] = "temp-XXXXX";

  if( /** infile == stdin *//)
  {
    mkstemp(temp_path);
    *data.infile = temp_path;
  }

  //do stuff and return

}

基本上,我要做的是检测用户是否想要从stdin输入数据,如果是,请创建一个临时文件,我可以在其中执行操作。

这里的问题是,当我设置如上所示的infile路径时,退出函数时不会保留该数据,因为它是一个局部变量。因此,当我退出函数时,临时文件路径在结构中丢失。除了物理复制字符串之外,还有什么我可以做的来保留这个值吗?

2 个答案:

答案 0 :(得分:2)

data->infile = strdup(temp_path);

答案 1 :(得分:1)

  

除了物理复制字符串外,还有什么我可以做的来保留这个值吗?

你可以声明它static,它会让"字符串"为整个节目的实时时间而活。

static char temp_path[] = "temp-XXXXX";

但请注意,temp_path只存在一次,因此多线程访问它可能会导致混淆。