如何使用fgetpwent()?

时间:2014-03-21 10:53:24

标签: c linux

我正在尝试获取系统中所有用户的列表(linux,fedora)。 并且我听说过功能:fgetpwent是我完成该任务所需要的功能。 可悲的是,我没有找到任何文档或如何使用此功能的示例。 如果有人愿意给我一个例子,那就太好了,先谢谢。

1 个答案:

答案 0 :(得分:2)

不知道为什么我曾经用过它:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crypt.h>
#include <pwd.h>
#include <sys/types.h>

char *testentry = "testread";

static void read_etc_passwd (void) {
  struct passwd *pwd_entry = NULL;

  int found = 0;

  setpwent(); // go to the top of /etc/passwd

  while (!found && (pwd_entry = getpwent())){
    if (0 == strcmp (testentry, pwd_entry->pw_name)){
        found = 1;
    }
  }
  if (found) {
    printf ("name = %s\nhome = %s\n", pwd_entry->pw_name,
            pwd_entry->pw_dir);
  } else {
    puts("could not find the entry you were looking for, or"
         "some error occurred");
  }
}


void change_etc_passwd (void){
  struct passwd *pwd = NULL;
  FILE *pwd_fd = NULL;
  FILE *pwd_new = NULL;
  int result = 0;


  pwd_fd = fopen ("/etc/passwd", "r");
  pwd_new = fopen ("/tmp/passwd.neu", "a");

  // assuming everthing went fine (bad idea)
  while (pwd = fgetpwent (pwd_fd)){
    if (0 == strcmp (pwd->pw_name, testentry)){
      pwd->pw_passwd = crypt ("new_pwd", "aa");
    }
    result = putpwent(pwd, pwd_new);
    if (result < 0){
      fprintf (stderr, "Failed to write entry, giving up\n");
      exit (EXIT_FAILURE);
    }
  }
}



int main (void) {
  /* handling of /etc/passwd */
  read_etc_passwd ();
  change_etc_passwd();
  return 0;
}

添加错误处理,甚至可以不中断; - )