C语言 我需要定义更多的strtok函数吗?

lf5gs5x2  于 2023-02-07  发布在  其他
关注(0)|答案(1)|浏览(128)

我想运行一个命令行参数来解释用户名、名字、电子邮件和主目录。我把用户名部分写对了,但其余部分放错了地方。我不知道我是否把strtok函数放在了正确的位置,每次我编译时,它都会错误地输出“变量未使用”。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
  if (argc != 2) {
    printf("Usage: %s <username>\n", argv[0]);
    return 1;
  }

  char *username = argv[1];

  FILE *passwd = fopen("/etc/passwd", "r");
  if (!passwd) {
    perror("fopen");
    return 1;
  }

  char *line = NULL;
  size_t max_length = 0;
  ssize_t ret_val = 0;
  char line_copy[1000];

  while ((ret_val = getline(&line, &max_length, passwd)) > 0) {
    strncpy(line_copy, line, 999);

    char *user = strtok(line_copy, ":");
    if (strcmp(user, username) == 0) {
      char *name = strtok(NULL, ":");
      char *email = strtok(NULL, ":");
      char *home_dir = strtok(NULL, ":");

      printf("user: %s\n", user);
      printf("name: %s\n", name);
      printf("email: %s\n", email);
      printf("home directory: %s\n", home_dir);
    }
  }

  fclose(passwd);
  passwd = NULL;

  return 0;
}
hs1ihplo

hs1ihplo1#

至少在Linux上/etc/passwd包含以冒号分隔的字段登录名、密码、用户ID、组ID、用户名、主目录和shell。您需要调用strtok()来获取您想要跳过的字段,并且没有电子邮件字段:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <username>\n", argv[0]);
        return 1;
    }
    char *username = argv[1];

    FILE *passwd = fopen("/etc/passwd", "r");
    if (!passwd) {
        perror("fopen");
        return 1;
    }

    char *line = NULL;
    size_t max_length = 0;
    ssize_t ret_val;
    while ((ret_val = getline(&line, &max_length, passwd)) > 0) {
        if (strcmp(username, strtok(line, ":")) == 0) {
            strtok(NULL, ":"); // password
            strtok(NULL, ":"); // uid
            strtok(NULL, ":"); // gid
            char *name = strtok(NULL, ":");
            char *home_dir = strtok(NULL, ":");
            printf("user: %s\n", username);
            printf("name: %s\n", name);
            printf("home directory: %s\n", home_dir);
        }
        return 0;
    }
    fclose(passwd);
    return 1;
}

请考虑改用getpwnam()

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <username>\n", argv[0]);
        return 1;
    }
    struct passwd *pw = getpwnam(argv[1]);
    if(!pw)
        return 1;

    printf("user: %s\n", pw->pw_name);
    printf("name: %s\n", pw->pw_gecos);
    printf("home directory: %s\n", pw->pw_dir);
}

相关问题