[英]Modifying C string within a structure pointer
I have code that looks something like this: 我有看起来像这样的代码:
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
}
Basically, what I'm trying to do is detect if the user wants to input data from stdin
and if so make a temporary file where I can do stuff. 基本上,我要尝试的是检测用户是否要从
stdin
输入数据,如果是,请创建一个临时文件以供我处理。
The problem here is that when I set my infile path as shown above, that data is not retained upon exiting the function because it's a local variable. 这里的问题是,当我如上所述设置文件路径时,由于该函数是局部变量,因此在退出函数时不会保留该数据。 So when I exit the function the temporary file path is lost in the structure.
因此,当我退出函数时,临时文件路径会在结构中丢失。 Other than physically copying the string, is there anything else I can do to retain the value?
除了物理复制字符串之外,我还能做些其他事情来保留值吗?
data->infile = strdup(temp_path);
Other than physically copying the string, is there anything else I can do to retain the value?
除了物理复制字符串之外,我还能做些其他事情来保留值吗?
You can declare it static
, which would let the "string" live for the whole program's live time. 您可以将其声明为
static
,这将使“字符串”在整个程序的生存期内保持生存。
static char temp_path[] = "temp-XXXXX";
But be aware, that temp_path
exists only once, so accessing it by multiple threads might lead to confusion. 但是请注意,
temp_path
仅存在一次,因此由多个线程访问它可能会引起混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.