使用C中的snprintf将所有argv值连接到一个字符串

时间:2011-04-26 21:08:00

标签: c concatenation command-line-arguments printf

如何使用snprintf将argv中的所有值连接到一个字符串?

如果我传递./prog val1 val2 val3 val4

之类的值

我的字符串  char all_values[MAX_LEN]应为“val1 val2 val3 val4

如何使用snprintf()高效地完成此操作?

3 个答案:

答案 0 :(得分:6)

#include <stdio.h>

#define MAX_LEN 16
int main(int ac, char **av) {
   char buffer[MAX_LEN];
   buffer[0] = 0;
   int offset = 0;
   while(av++,--ac) {
      int toWrite = MAX_LEN-offset;
      int written = snprintf(buffer+offset, toWrite, "%s ", *av);
      if(toWrite < written) {
          break;
      }
      offset += written;
   }
   printf("%s\n", buffer);
}

答案 1 :(得分:1)

如果你想要打印N个参数,你可以做

int i = 1 ; // first parameter is a program name  
while(i < argc )
{
   printf("%s",argv[1]);
   i++;
}

但是如果你想在其他处理器中使用一个字符串,那么你真的会连接它。也许与:

char* string_result; 

int  i = 1; 

int  size_total = 0;
bool space_needed = false;

while(i < argc) { // argc contain the number of arguments
   size_total += strlen(argv[i])+1; //+1 for a new space each time.
   i++;
}

if(i > 2) {
    space_needed = true;
    size_total -= 1; //no need for space at end of string
}

string_result = (char*)malloc((size_total+1)*sizeof(char));

string_result[0] = 0 ; // redundant?

i = 1;

while(i < argc) {
   strcat(string_result,argv[i]); // caution to concatenate argv string, memory of OS. 
   if(space_needed && (i+1) < argc)
        strcat(string_result, " "); //space so it looks better.
   i++;
}

//free pointer when done using it.
free(string_result);

答案 2 :(得分:0)

假设sizoeof(char)== 1,未经测试的代码!

#include <stdlib.h>
#include <string.h>

    int  i ; 
    int  size_total = 0;
    size_t *lens=(size_t *)malloc((argc)*sizeof(size_t));
    for (i=1;i < argc; i++) {
        lens[i]=strlen(argv[i]);
        size_total += lens[i]+1;
    }
    concatinated = (char*)malloc(size_total);
    char *start=concatinated;
    for (i=1;i < argc; i++) {
        memcpy(start, argv[i], lens[i]);
        start+=lens[i];
        *start=' ';
        start++;
    }
    start--;
    *start=0;
    free(lens);