次のコードは、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 標準の拡張として、Linux (libc4、libc5、glibc) の getcwd() は、buf が NULL の場合、malloc(3) を使用して動的にバッファーを割り当てます。この場合、必要な大きさの buf が割り当てられている場合、size がゼロでない限り、割り当てられたバッファの長さは size になります。呼び出し元は、返されたバッファを free(3) する必要があります。
どうやら、_getcwd() は MS Windows でも同じように動作します。_getcwd() に関するMSDN の状態:
_getcwd 関数は、既定のドライブの現在の作業ディレクトリの完全なパスを取得し、それをバッファーに格納します。整数引数 maxlen は、パスの最大長を指定します。パスの長さ (終端のヌル文字を含む) が maxlen を超えると、エラーが発生します。buffer 引数は 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;
}