修改结构指针中的C字符串
Modifying C string within a structure pointer
我有这样的代码:
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
输入数据,如果是,请创建一个临时文件,在那里我可以做一些事情。
这里的问题是,当我如上所示设置内野路径时,数据在退出函数时不会被保留,因为它是一个局部变量。因此,当我退出函数时,临时文件路径会在结构中丢失。除了物理复制字符串之外,我还能做些什么来保留值吗?
data->infile = strdup(temp_path);
除了物理复制字符串之外,我还能做些什么来保留值吗?
您可以将其声明为static
,这将使"字符串"在整个程序的活动时间内活动。
static char temp_path[] = "temp-XXXXX";
但请注意,temp_path
只存在一次,因此由多个线程访问它可能会导致混淆。
相关文章:
- C++结构到字符串
- 从字符串中获取结构的大小
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何解析表示树状数据结构的字符串
- 如何将字符串与结构(也包括字符串)进行比较?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 将字符串存储在 constexpr 结构中
- 为什么我的结构在包含字符串时崩溃?
- 如何将字符串字符与结构数组进行比较?
- 无法使用 strcpy 将字符串复制到静态结构成员
- c++ 将函数参数(带有模板变量的结构)转换为函数体内的字符串
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- C++使用旧编译器GCC 4.4.0在结构列表中查找字符串
- 具有字符串成员的结构的动态数组
- 如何将文本文件保存到C 中的字符串结构
- C++ 斯特劳斯特鲁普的"std_lib_facilities.h"字符串结构 – 警告:无符号表达式的比较
- C++:字符串结构相等
- 返回字符串结构是否安全