C language fgetgrent of function and fgetpwent of function usage comparison

  • 2020-04-02 03:19:56
  • OfStack

C language fgetgrent() function: read the group format function

The header file:


#include <grp.h>  #include <stdio.h>  #include <sys/types.h>

Definition function:


struct group * getgrent(FILE * stream);

Fgetgrent () reads a line of data from the file specified by the parameter stream and returns it in a group structure. The file specified by the parameter stream must be in the same format as, etc/group.

Return value: returns group structure data. If NULL is returned, there is no data or an error has occurred.

sample


#include <grp.h>
#include <sys/types.h>
#include <stdio.h>
main()
{
  struct group *data;
  FILE *stream;
  int i;
  stream = fopen("/etc/group", "r");
  while((data = fgetgrent(stream)) != 0)
  {
    i = 0;
    printf("%s :%s:%d :", data->gr_name, data->gr_passwd, data->gr_gid);
    while(data->gr_mem[i])
      printf("%s, ", data->gr_mem[i++]);
    printf("n");
  }
  fclose(stream);
}

Perform:


root:x:0:root,
bin:x:1:root, bin, daemon
daemon:x:2:root, bin, daemon
sys:x:3:root, bin, adm
adm:x:4:root, adm, daemon
tty:x:5
disk:x:6:root
lp:x:7:daemon, lp
mem:x:8
kmem:x:9
wheel:x:10:root
mail:x:12:mail
news:x:13:news
uucp:x:14:uucp
man:x:15
games:x:20
gopher:x:30
dip:x:40:
ftp:x:50
nobody:x:99:

C fgetpwent() function: reads the password format

The header file:


#include <pwd.h>  #include <stdio.h>  #include <sys/types.h>

Definition function:


struct passwd * fgetpwent(FILE * stream);

Fgetpwent () reads a line of data from the file specified by the argument stream and returns it in the passwd structure. The file specified by the argument stream must be in the same format as /etc/passwd.

Return value: returns the passwd structure data. If NULL is returned, there is no data or an error has occurred.

sample


#include <pwd.h>
#include <sys/types.h>
main()
{
  struct passwd *user;
  FILE *stream;
  stream = fopen("/etc/passwd", "r");
  while((user = fgetpwent(stream)) != 0)
  {
    printf("%s:%d:%d:%s:%s:%sn", user->pw_name, user->pw_uid, user->pw_gid,
    user->pw_gecos, user->pw_dir, user->pw_shell);
  }
}

Perform:


root:0:0:root:/root:/bin/bash
bin:1:1:bin:/bin:
daemon:2:2:daemon:/sbin:
adm:3:4:adm:/var/adm:
lp:4:7:lp:/var/spool/lpd:
sync:5:0:sync:/sbin:/bin/sync
shutdown:6:0:shutdown:/sbin:/sbin/shutdown
halt:7:0:halt:/sbin:/sbin/halt
mail:8:12:mail:/var/spool/mail:
news:9:13:news:var/spool/news
uucp:10:14:uucp:/var/spool/uucp:
operator:11:0:operator :/root:
games:12:100:games:/usr/games:
gopher:13:30:gopher:/usr/lib/gopher-data:
ftp:14:50:FTP User:/home/ftp:
nobody:99:99:Nobody:/:
xfs:100:101:X Font Server: /etc/Xll/fs:/bin/false
gdm:42:42:/home/gdm:/bin/bash
kids:500:500: : /home/kids:/bin/bash


Related articles: