下面的代码演示了如何使用 strcat() 来构建一个包含所有 argv[] 元素的字符串:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i;
size_t outputSize = 1;
char *output = NULL;
/* Allocate a buffer large enough to hold the string termination character. */
output=malloc(outputSize);
if(!output)
{
fprintf(stderr, "malloc() failed.\n");
goto CLEANUP;
}
*output = '\0';
/* Iterate argv[] elements. */
for(i = 0; i < argc; i++)
{
char *tmp;
/* Increase the size of the output buffer to hold this argv[] element. */
outputSize += strlen(argv[i]);
tmp=realloc(output, outputSize);
if(!tmp)
{
fprintf(stderr, "realloc() failed.\n");
goto CLEANUP;
}
output=tmp;
/* Concatinate this argv[] element to the output string. */
strcat(output, argv[i]);
}
/* Print the result. */
printf("%s\n", output);
CLEANUP:
if(output)
free(output);
return 0;
}
在 Linux 上,您还可以包含当前工作目录的路径,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int i;
size_t outputSize;
char *output = NULL;
output=getcwd(NULL,0);
if(!output)
{
fprintf(stderr, "getcwd() failed.\n");
goto CLEANUP;
}
outputSize = strlen(output) + 1;
for(i = 0; i < argc; i++)
{
char *tmp;
outputSize += strlen(argv[i]);
tmp=realloc(output, outputSize);
if(!tmp)
{
fprintf(stderr, "realloc() failed.\n");
goto CLEANUP;
}
output=tmp;
strcat(output, argv[i]);
}
printf("%s\n", output);
CLEANUP:
if(output)
free(output);
return 0;
}
由于对“getcwd()”的 Linux 扩展,上面的示例是特定于 Linux 的。Linux getcwd 手册页指出:
作为 POSIX.1-2001 标准的扩展,如果 buf 为 NULL,Linux (libc4, libc5, glibc) getcwd() 使用 malloc(3) 动态分配缓冲区。在这种情况下,分配的缓冲区具有长度大小,除非大小为零,当 buf 被分配到必要的大小时。调用者应该释放(3)返回的缓冲区。
显然, _getcwd() 在 MS Windows 上的工作方式相同。MSDN关于 _getcwd() 的状态:
_getcwd 函数获取默认驱动器当前工作目录的完整路径并将其存储在缓冲区中。整数参数 maxlen 指定路径的最大长度。如果路径的长度(包括终止空字符)超过 maxlen,则会发生错误。缓冲区参数可以为 NULL;使用 malloc 自动分配至少大小为 maxlen 的缓冲区(仅在必要时更大)来存储路径。稍后可以通过调用 free 并将 _getcwd 返回值(指向已分配缓冲区的指针)传递给该缓冲区来释放此缓冲区。
因此,也许以下(未经测试的)代码适用于 MS Windows 环境:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <direct.h>
int main(int argc, char *argv[])
{
int i;
size_t outputSize;
char *output = NULL;
output=_getcwd(NULL,0);
if(!output)
{
fprintf(stderr, "_getcwd() failed.\n");
goto CLEANUP;
}
outputSize = strlen(output) + 1;
for(i = 0; i < argc; i++)
{
char *tmp;
outputSize += strlen(argv[i]);
tmp=realloc(output, outputSize);
if(!tmp)
{
fprintf(stderr, "realloc() failed.\n");
goto CLEANUP;
}
output=tmp;
strcat(output, argv[i]);
}
printf("%s\n", output);
CLEANUP:
if(output)
free(output);
return 0;
}