【问题标题】:concatenate all argv values to one string using snprintf in C在 C 中使用 snprintf 将所有 argv 值连接到一个字符串
【发布时间】:2011-04-26 21:07:59
【问题描述】:

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

如果我传入像 ./prog val1 val2 val3 val4 这样的值

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

如何使用snprintf() 有效地做到这一点?

【问题讨论】:

  • 这是作业题吗?我只是问,因为它会影响我给出的答案的准确程度。
  • 不,这不是作业问题。我已经有一段时间没有在 C 中工作了,我无法正确解决这个问题。
  • 您为什么对使用 snprintf() 感兴趣?相反,例如,strcat()?
  • 如果您的目标是通过system 或其他方式将它们传递给另一个程序,这是一种非常糟糕的方法。请改用execv 或类似名称。

标签: c concatenation command-line-arguments printf


【解决方案1】:
#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);
}

【讨论】:

  • 不需要buffer[MAX_LEN-1] = 0;,因为“超过第n-1个的输出字节应被丢弃而不是写入数组,并且在实际写入的字节末尾写入一个空字节数组”(POSIX,pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
  • 谢谢。我在 Linux 手册页上工作,但找不到保证。我将编辑我的答案。
【解决方案2】:

如果你想打印 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);

【讨论】:

    【解决方案3】:

    假设 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);
    

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多