我一直在想办法(在 C 中)将“getenv()”和“/filetest”放入一个字符中。
我认为你可以通过放置来做到这一点:
char *file = getenv("HOME") + "/filetest";
但是,我似乎无法弄明白。
之后我尝试这样做:
char *file = getenv("HOME") && "/filetest";
但这也不管用..
然后,我试过:
char *file1 = getenv("HOME");
char *file = file1 + "/filetest";
有人可以告诉我我做错了什么吗?
在 C 中,字符串复制/连接由 strcpy / strcat 执行:
https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char file[200];
strcpy(file, getenv("HOME"));
strcat(file, "/filetest");
printf("%s", file);
printf("\n\n");
return 0;
}
分配一个足够大的缓冲区来容纳这两个字符串,然后使用
strcat()
将string2连接到string1:
char buffer[BUFSIZ];
strcat (strcpy (buffer, getenv ("HOME"), "/filetest");
/* OR */
unsigned offset = 0;
strcpy (buffer + offset, tmp);
offset += strlen (tmp);
strcpy (buffer + offset, "/filetest");
/* OR */
strcpy (buffer, tmp);
strcpy (buffer + strlen (tmp), "/filetest");
注意
getenv()
通过返回 NULL
指针常量表示失败,代码应在调用 strcpy()
之前检查其结果。
char *tmp = getenv ("HOME");
if (!tmp) {
complain ();
}
/* Now copy. */