How do i put a string and user input into a new string using strcpy?

时间:2015-10-30 23:22:54

标签: c string shell

Sorry if the title is a little bit confusing but basically im trying to make a command that will change the default shell of a user. The user just needs to call the command (btb) and input the username e.g. btb USERNAME btb being args[0] and USERNAME being args[1]. Now i need to make this into one string so that i can use it to make a system call system("chsh -s /bin/bash USERNAME"). So far i have this int Registerbtb(char **args) { char command[50]; strcpy(command, args[1]); system(command); return 1; } which is only taking the args[1] and putting that into command. But i need it to do is strcpy(command, ("chsh -s /bin/bash %s", args[1])); but that isnt possible. What other way can i do this so that command will have the string "chsh -s /bin/bash USERNAME" in it

1 个答案:

答案 0 :(得分:1)

strcpy is not the function you're looking for. You should instead use snprintf with a buffer to hold your string, if you know the size: char buf[50]; snprintf(buf, sizeof(buf), "chsh -s /bin/bash %s", args[1]); Keep in mind this above example suffers from a potential bug where the string will be truncated. If you don't know the size of the username in beforehand you can call snprintf twice to dynamically allocate memory for your string, here is an example program. #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); } Or if you have it available on your system you can just use asprintf to save you from an headache.