gpt4 book ai didi

c - 段错误(核心转储)C linux

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:52 25 4
gpt4 key购买 nike

所以我必须制作一个程序,其执行结果与在 linux 中使用命令 who and who am i 后的结果相似。问题是 if(strcmp... 和 else... 中的两个函数在分开时都在工作。

主要问题是我必须将它们都放在一个文件中,但它不起作用。当只放在一起做某事时,./program 是我,./program 告诉 Segmentation fault (core dumped)。

第二个问题是我不知道如何制作部分 ./program 我是否正常工作它应该只返回我:用户 pts/0 日期时间...并非所有用户都喜欢 else...部分。

#include    <stdio.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>

#define SHOWHOST

void show_info_who( struct utmp *utbufp )
{
if(utbufp->ut_type > 4){
time_t czas = utbufp->ut_time;
char buf[80];
struct tm* timeinfo = localtime(&czas);

printf("%-8.8s", utbufp->ut_name);
printf(" ");
printf("%-8.8s", utbufp->ut_line);
printf(" ");
strftime(buf, 80, "%F %R" , timeinfo);
printf("%s", buf);
printf(" ");


#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host);
#endif
printf("\n");
}
}


int main(int argc, char *argv[])
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);

if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
perror( UTMP_FILE );
exit(1);
}

if(strcmp ( argv[1], "am") == 0){
if(strcmp ( argv[2], "i") == 0){
while ( read(utmpfd, &current_record, reclen) == reclen )
show_info_who(&current_record);
printf("test\n");
}

close(utmpfd);
return 0;
}

while ( read(utmpfd, &current_record, reclen) == reclen )
show_info_who(&current_record);
close(utmpfd);

return 0;


}

最佳答案

你为什么不尝试使用,

void setutent(void); // for rewinding
struct utmp *getutent(void);

不推荐直接打开查找utmp文件。utmp 文件看似是一个可以自由访问的普通文件,但它的行为就像一个数据库。

关于c - 段错误(核心转储)C linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33673405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com