ç串联可变长度的int一个字符串,而不进行打印 [英] c concatenate variable length int to a string without printing it
问题描述
我需要连接到一个系统调用字符串整数:
I need to concatenate an integer to a system call string:
状态=系统(./运行的test.txt+整数);
整数
在这里可以是任何int类型。
integer
here can be any int.
什么是这样做的最佳方式?
What is the best way of doing this?
推荐答案
使用 的snprintf
(或 的sprintf
如果你没有的snprintf
或需要您的code到没有它系统上运行)打印到字符缓冲区,并传递到系统
电话。
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.
例如
#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的回答说明了这一点。请注意,这可能不是一个很好的策略,如果你不能使用沃拉斯(C89),并有原因,以避免的malloc()
,例如一些嵌入式系统。
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()
, e.g. on some embedded systems.
这篇关于ç串联可变长度的int一个字符串,而不进行打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!