简体   繁体   中英

c concatenate variable length int to a string without printing it

I need to concatenate an integer to a system call string:

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

integer here can be any int.

What is the best way of doing this?

Use snprintf (or sprintf if you don't have snprintf or need your code to run on systems without it) to print to a char buffer, and pass that to the system call.

eg

#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);

Alternatively, you could calculate how many characters the integer needs and then allocate an exactly correctly sized buffer. This would allow you to use sprintf safely and removes the need to check for truncation - chux's answer demonstrates this. Note that this may not be a good strategy if you cannot use VLAs (C89) and have reasons to avoid malloc() , eg on some embedded systems.

After accept answer

Use a right-sized buffer via VLA or malloc() . Estimating a fixed buffer size may overflow the buffer with sprintf() or create a truncated result with 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);

The INT_PRINT_SIZE(i) macro returns the char size needed to accommodate decimal representation of integer type i . With some integer types, the result may be 1 or 2 extra, but is never too small. Alternatively, code could use 10*sizeof(type)*CHAR_BIT/33 + 3 which has less extra overhead. The idea is to multiple the bit width by some integer a/b fraction that is near and >= log10(2) or ~0.30103. This size does include the char need for the trailing '\\0' . So the above char buf[] does not need the trailing + 1 .

Using sprintf :

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

see man sprintf

char buf[150];

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

Make sure buf isn't too small.

#define COMMAND_SIZE 100

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM