簡體   English   中英

c將可變長度int連接到字符串而不打印它

[英]c concatenate variable length int to a string without printing it

我需要將整數連接到系統調用字符串:

status = system("./run test.txt " + integer);

integer可以是任何整數。

最好的方法是什么?

使用snprintf (如果沒有snprintf或需要代碼在沒有它的系統上運行,則使用sprintf )打印到char緩沖區,並將其傳遞給system調用。

例如

#define MAX_LEN 128
char buffer[MAX_LEN];
int val = 0;
snprintf(buffer, MAX_LEN, "./run test.txt %d", val);

// you would be wise to check that snprintf has not truncated your command
// before passing it to system()
status = system(buffer);

或者,您可以計算整數需要多少個字符,然后分配大小正確正確的緩沖區。 這將允許您安全地使用sprintf ,而無需檢查截斷-chux的答案證明了這一點。 請注意,如果您不能使用VLA(C89)並且有避免使用malloc()理由malloc()例如在某些嵌入式系統上malloc() ,那么這可能不是一個好的策略。

接受答案后

通過VLAmalloc()使用大小合適的緩沖區。 估計固定的緩沖區大小可能會使sprintf()溢出緩沖區,或者使用snprintf()產生截斷的結果。

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

int system_command_int(const char *command, int i) {
  #define INT_PRINT_SIZE(i) ((sizeof(i) * CHAR_BIT)/3 + 3)
  char buf[strlen(command) + 1 + INT_PRINT_SIZE(i) + 1];

  sprintf(buf, "%s %d",command, i);
  return system(buf);
}

int status = system_command_int("./run test.txt", integer);

INT_PRINT_SIZE(i)宏返回容納整數類型i十進制表示形式所需的char大小。 對於某些整數類型,結果可能會額外增加1或2,但永遠不會太小。 或者,代碼可以使用10*sizeof(type)*CHAR_BIT/33 + 3 ,這會減少額外的開銷。 想法是將位寬度乘以接近且> = log10(2)或〜0.30103的某個整數a / b分數。 此大小確實包含尾隨'\\0'char需求。 因此,上面的char buf[]不需要結尾+ 1

使用sprintf

char buffer[256];
sprintf(buffer,"./run test.txt %d",integer);
status = system(buffer);

見男人sprintf

char buf[150];

sprintf(buf, "./run test.txt %d", integer);
status = system(buf);

確保buf不太小。

#define COMMAND_SIZE 100

char command[COMMAND_SIZE];
sprintf(command, "./run test.txt %d", integer);
status = system(command);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM