【发布时间】:2012-04-11 19:38:19
【问题描述】:
我是 C 的新手,并尝试实现 whoami,作为我自己的练习。我有以下代码:
#define _POSIX_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h> // strtok
int str_to_int(const char *str)
{
int acc = 0;
int i;
for (i = 0; str[i] != '\0'; ++i) {
acc = (10 * acc) + (str[i] - 48); // 48 -> 0 in ascii
}
return acc;
}
int main()
{
FILE *passwd;
char *line = NULL;
size_t line_size;
passwd = fopen("/etc/passwd","r");
uid_t uid = getuid();
while (getline(&line, &line_size,passwd) != -1) {
char *name = strtok(line,":");
strtok(line,":"); // passwd
char *user_id = strtok(line,":");
if (str_to_int(user_id) == uid) {
printf("%s\n",name);
break;
}
}
fclose(passwd);
return 0;
}
我是否需要在 while 循环内保存行指针。因为我认为 strtok 以某种方式对其进行了修改,但我不确定是否需要复制该行或该行的起始地址,然后再将其与 strtok 一起使用。
【问题讨论】:
-
您可以使用
atoi或strtol将字符串转换为整数,而不是您的自定义函数。