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

最佳答案

不知道为什么我会用它:

#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;
}

添加错误处理,甚至可以在不中断的情况下工作;-)

关于c - 如何使用fgetpwent()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22556749/

10-11 21:31