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


sorry if title little bit confusing im trying make command change default shell of user.

the user needs call command (btb) , input username e.g. btb username btb being args[0] , username being args[1]. need make 1 string can use make system call system("chsh -s /bin/bash username").

so far have this

int registerbtb(char **args) {   char command[50];   strcpy(command, args[1]);   system(command);   return 1; } 

which taking args[1] , putting command. need strcpy(command, ("chsh -s /bin/bash %s", args[1])); isnt possible.

what other way can command have string "chsh -s /bin/bash username" in it

strcpy not function you're looking for. should instead use snprintf buffer hold string, if know size:

char buf[50]; snprintf(buf, sizeof(buf), "chsh -s /bin/bash %s", args[1]); 

keep in mind above example suffers potential bug string truncated.

if don't know size of username in beforehand can call snprintf twice dynamically allocate memory string, here example program.

#include <stdio.h> #include <stdlib.h> #include <assert.h>  int main(int argc, char **args) {   char *str;    // todo check if argc equal 1    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); // str   free(str); } 

or if have available on system can use asprintf save headache.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -