C 如何在仍然能够重用其中一个参数(变量)的情况下连接两个字符串(一个是变量)?

C 如何在仍然能够重用其中一个参数(变量)的情况下连接两个字符串(一个是变量)?,c,strcpy,strcat,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(dirP

我知道有人问过这个问题,但我看到的答案并不适用于我的案例。在我的程序结束时,打开了一堆文件进行编写。为了简单起见,我将列表限制为两个。变量
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不返回连接字符串的副本,而是将第2个参数附加到第1个参数。在查找工作时,我发现,要同时使用strcpy和strcat,或者使用sprintf

我第一次尝试sprintf,但遇到一个错误,即我试图在其中传递一个
int
,其中需要
char*
,即使
dirPath
声明为
char*
。我还尝试传入一个字符串文本,但运气不好

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

唯一的办法是:

char temp_dir_path[256];
strcpy(temp_dir_path, dirPath);
fid_sensory_output = fopen(strcat(temp_dir_path, "sensory_output"), "w");
strcpy(temp_dir_path, dirPath);
fid_msn_output = fopen(strcat(temp_dir_path,"msn_output"), "w");
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);

您可以使用snprintf完成此任务。每个字符串操作都应考虑缓冲区大小以避免缓冲区溢出。

snprintf返回写入缓冲区的字符数(不包括字符串终止符“\0”)

FILE *fid_sensory_output;
FILE *fid_msn_output;
char path[MAX_PATH];

snprintf(path, sizeof(path), "%s/%s", dirPath, "sensory_output");
fid_sensory_output = fopen(path, "w");

snprintf(path, sizeof(path), "%s/%s", dirPath, "msn_output");
fid_msn_output = fopen(path, "w");