学会使用fsetpos fgetpos fscanf fprintf等函数的使用
#include <stdio.h> #include <string.h> #include <utmp.h> #include <stdlib.h>
int main(void) { FILE *fp,*fp1,*fp2; struct utmp utmp_buf; fpos_t pos; int num=0,cur_num=0; if( (fp=fopen( "/var/run/utmp","r"))==NULL ) { perror("error when open the file ! \n"); exit(1); } if( (fp1=fopen( "/tmp/utmp_info","w"))==NULL ) { perror("error when open the file ! \n"); exit(1); } while( (fread(&utmp_buf,sizeof(struct utmp),1,fp))>0 ) { num++; printf("current_use: %s \n",utmp_buf.ut_user); fprintf(fp1,"current_use: %s \n",utmp_buf.ut_user); } printf("now, read for the last 4 line \n"); fseek(fp,-4*sizeof(struct utmp),SEEK_END); while( (fread(&utmp_buf,sizeof(struct utmp),1,fp))>0 ) { printf("current_use: %s \n",utmp_buf.ut_user); }
printf("now,use fsetpos\fgetpos to read last 4 line \n"); rewind(fp); while( (fread(&utmp_buf,sizeof(struct utmp),1,fp))>0 ) { cur_num++; if( cur_num==(num-4) ) { fgetpos(fp,&pos); break; } } fsetpos(fp,&pos); while( (fread(&utmp_buf,sizeof(struct utmp),1,fp))>0 ) { printf("current_use: %s \n",utmp_buf.ut_user); }
fclose(fp); }
|