concatenate all argv values to one string using snprintf in C
How can I concatenate all the values in argv to one string using snprintf?
if i pass in values like ./prog val1 val2 val3 val4
my string
char all_values[M开发者_如何转开发AX_LEN]
should be "val1 val2 val3 val4
"
How can I do this efficiently using snprintf()
?
#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);
}
If you to want make a print of N arguments, you can do
int i = 1 ; // first parameter is a program name
while(i < argc )
{
printf("%s",argv[1]);
i++;
}
But if you want to use a string in other processor,you would really concatenate then. Maybe with:
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);
Assuming sizoeof(char)==1, untested code!
#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);
精彩评论