Adding user using C++

Hi, I'm new to this, therefore i would like to enquire on some idea to get me starting.

- What kind of head do I need
- What is the code i need for inputing into command of accessing a /root/etc/passwd

or i can jus pass a code of fstream?

Thank alot in advance really struck now.
You need to use something like putpwent()

type man putpwent in a terminal window or google for more info
Last edited on
I would've generated the cmdline arguements for useradd/adduser and used exec();.

:D But I am lazy
Thanks alot, bnertha, I wouldn;t have do it without your hint, I got my start kick off well, but struck with the function putpwent(). I do not understand the constraint and stream needed to be inside(). I'm nw able to call out the pwd.h and display it's contain. Can u advise more on the putpwent(), like what do i need in it. Thanks again.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>



int main(int argc, char ** argv)
{
struct passwd *p_entry;
FILE *f;
char username[]="derek";
char homedir[]="/tmp/derek";
char uid[]="1005";


scanf("%s", username);

f=fopen("mypdb.db ", "a+");
fseek(f, 0, SEEK_END);
p_entry = getpwent();
p_entry -> pw_name =username;
p_entry -> pw_name =homedir;
p_entry -> pw_uid = int (uid);


if (putpwent(p_entry, f) == -1) {
return -1;


}

else
putpwent(p_entry, f);

fflush(stdout);

fclose(f);
return 1;


}

I can't write into the file? what's wrong do i need something like a container or so? it return's segmentation fault.

getpwent() gets the next entry in the password file. Each time it is called it gets the next entry from that password file. If you are just adding you don't need to do this. You are also getting an entry from the end of the file so it may be a non-existent entry.

I'm not sure why you are calling putpwent twice if the first one succeeds

Finally you can't use '=' to assign a char array. You need to strcpy()
Last edited on
Topic archived. No new replies allowed.