我知道有人问过这个问题,但我看到的答案并不适用于我的情况。在我的程序结束时,打开了一堆文件进行写入。为简单起见,我将列表限制为两个。变量 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/