抱歉,标题有点混乱,但是基本上我试图创建一个将更改用户默认外壳的命令。
用户只需要调用命令(btb)并输入用户名即可,例如btb USERNAME
btb为args [0],而USERNAME为args [1]。现在,我需要将其变成一个字符串,以便可以使用它进行系统调用system("chsh -s /bin/bash USERNAME")
。
到目前为止,我有这个
int Registerbtb(char **args)
{
char command[50];
strcpy(command, args[1]);
system(command);
return 1;
}
这只是将args [1]放入命令中。但是我需要做的是strcpy(command, ("chsh -s /bin/bash %s", args[1]));
那是不可能的。
我能做到这一点有什么其他的方式,使命令将有串"chsh -s /bin/bash USERNAME"
在其
strcpy
不是您要寻找的功能。snprintf
如果知道大小,则应该改用缓冲区来保存字符串:
char buf[50];
snprintf(buf, sizeof(buf), "chsh -s /bin/bash %s", args[1]);
请记住,上面的示例存在一个潜在的错误,即字符串将被截断。
如果您事先不知道用户名的大小,则可以调用snprintf
两次以为字符串动态分配内存,这是一个示例程序。
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(int argc, char **args) {
char *str;
// TODO check if argc is equal to one
int length = snprintf(NULL, 0, "chsh -s /bin/bash %s", args[1]);
assert(length >= 0); // TODO add proper error handling
str = malloc(sizeof(char) * length);
snprintf(str, length, "chsh -s /bin/bash %s", args[1]);
printf("%s [%d]\n", str, length); // do something with the str
free(str);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句