c - 如何连接两个字符串(一个是变量)同时仍然能够重用其中一个参数(变量)?

标签 c strcpy strcat

我知道有人问过这个问题,但我看到的答案并不适用于我的情况。在我的程序结束时,打开了一堆文件进行写入。为简单起见,我将列表限制为两个。变量 dirPath 是在执行时传入的命令行参数。

这是我首先尝试的:

FILE *fid_sensory_output;
FILE *fid_msn_output;

fid_sensory_output = fopen(strcat(dirPath,"sensory_output"), "w");
fid_msn_output = fopen(strcat(dirPath,"msn_output"), "w");

这不起作用,因为 strcat 不返回串联字符串的副本,而是将第二个参数附加到第一个参数。在查找解决方法时,我发现了 these recommendations , 一起使用 strcpy 和 strcat,或者使用 sprintf。

我首先尝试了 sprintf,但出现了一个错误,提示我试图在需要 char * 的地方传递一个 int,即使 dirPath 声明为 char *。我也尝试过传递一个字符串文字,但没有成功。

我尝试以各种方式使用 strcat 和 strcpy,但均未成功。有什么建议吗?

最佳答案

唯一的办法:

FILE *fid_sensory_output;
char *string;

string=malloc(strlen(dirpath)+strlen("sensory_output")+1);
strcpy(string,dirpath);
strcat(string,"sensory_output");

fid_sensory_output = fopen(string, "w");
free(string);

关于c - 如何连接两个字符串(一个是变量)同时仍然能够重用其中一个参数(变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836591/

相关文章:

c - 我的输出显示了一些奇怪的符号

c -/proc的内核模块

c - 为什么我的代码输出 false,if(c>b>a) 会发生什么?

iphone - 在 Objective C/C 中将字符串中的数值转换为整数

c++ - 即使在将新字符串复制到现有字符串后,旧包含也可用(在某些索引处)

c - 段错误: 11 while trying to parse string

带有 fork execvp 管道和 dup2 的猫

C : how do I printf "the square root of 1764 is 42 and * in ascii"?

c - 尝试连接二维数组的元素时出现段错误

C 函数使用带有字符串的 strcat