I originally posted this thread in comp.unix.programmer. However, there hasn't been much traffic. I'm suspecting the regulars got some kind of life.
Anyhow the question stems from the following lines of code:
The problem line is:Code:#include <stdio.h> #include <utmp.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #define LOG "/var/run/utmp" static int process_type(struct utmp *user) { setutent(); if(user->ut_type == UT_UNKNOWN) printf("%12s:\t Unknown Process Type\n",user->ut_user); if(user->ut_type == RUN_LVL) printf("%12s:\t Run Level \n",user->ut_user); if(user->ut_type == BOOT_TIME) printf("%12s:\t Boot Time \n",user->ut_user); if(user->ut_type == NEW_TIME) printf("%12s:\t New Time \n",user->ut_user); if(user->ut_type == OLD_TIME) printf("%12s:\t Old Time \n",user->ut_user); if(user->ut_type == INIT_PROCESS) printf("%12s:\t Init \n",user->ut_user); if(user->ut_type == LOGIN_PROCESS) printf("%12s:\t Automatic Login \n",user->ut_user); if(user->ut_type == USER_PROCESS) printf("%12s:\t User account \n",user->ut_user); if(user->ut_type == DEAD_PROCESS) printf("%12s:\t Dead Process \n",user->ut_user); if(user->ut_type == ACCOUNTING) printf("%12s:\t Accounting \n",user->ut_user); endutent(); return 0; } static int user_info(struct utmp *user){ setutent(); printf("%12s %8s %22s %14s", user->ut_user, user->ut_line, user->ut_host, ctime(&user->ut_time) ); endutent(); return 0; } static int print_banner(void) { const char *name = "Name"; const char *term = "Terminal"; const char *host = "Hostname"; const char *time = "Time"; printf("%12s %10s %20s %3s\n",name,term,host,time); return 0; } static int print_process_type_banner(void) { int i; for(i=0;i<70;i++) { printf("-"); } printf("\n"); const char *name ="Name"; const char *type="Process Description"; printf("%12s \t %12s\n",name,type); return 0; } int main(int argc, char **argv) { struct utmp log_file; FILE *fp; print_banner(); if ((fp = fopen(LOG,"r")) != 0){ for(;fread(&log_file,sizeof(struct utmp),1,fp) !=0;) { user_info(&log_file); } if(!feof(fp)){ perror(argv[0]); exit(EXIT_FAILURE); } fclose(fp); } print_process_type_banner(); if(fp == NULL) { perror(argv[0]); exit(EXIT_FAILURE); } if ((fp = fopen(LOG,"r")) != 0) { for(;fread(&log_file,sizeof(struct utmp),1,fp) !=0;) { process_type(&log_file); } if(!feof(fp)){ perror(argv[0]); exit(EXIT_FAILURE); } fclose(fp); } if(fp == NULL) { perror(argv[0]); exit(EXIT_FAILURE); } return 0; }
Code:for(;fread(&log_file,sizeof(struct utmp),1,fp) !=0;)
I was told to use a while loop and check for error codes.
If I checked for error code using a while loop, would the following construction work:
Code:while(fread(&log_file,sizeof(struct utmp),1,fp) >=0){ if( (ferror(fp)) || feof(fp) ) exit(1); }



LinkBack URL
About LinkBacks


