![](/img/trans.png)
[英]How do you open a FILE with the user input and put it into a string in C
[英]How do i put a string and user input into a new string using strcpy?
抱歉,标题有点混乱,但是基本上我试图创建一个将更改用户默认外壳的命令。
用户只需要调用命令(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);
}
或者,如果您的系统上有它,则可以使用asprintf来使您免于头痛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.