c - Reading the linux utmp file without using fopen() and fread() -



c - Reading the linux utmp file without using fopen() and fread() -

i trying open utmp file in linux , read contents array of utmp structures. after display ut_user , ut_type each construction in array. have working when open file file *file , utilize fopen() , fread() functions when seek same task file descriptor int file , open() , read() functions address locations when trying access members of utmp structure.

so in below programme can see commented out 3 lines of code utilize perform task of reading utmp file array of utmp structures , print out 2 of members values. when seek doing exact same thing 3 lines of code (denoted "new way") in place of old way worked bunch of address locations rather values of ut_user , ut_id.

#include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <utmp.h> void utmpprint(struct utmp *log) { printf("\n ut_user: %s \n ut_type: %ld \n", log->ut_user, log->ut_type); } int main() { int logsize = 10; //file *file; //working way int file; //new way struct utmp log[logsize]; int = 0; //file = fopen("/var/run/utmp", "rb"); //working way file = open("/var/run/utmp", o_rdonly); //new way if( file < 0 ) { //new way printf("failed open"); return(0); } if (file) { //fread(&log, sizeof(struct utmp), logsize, file); //working way read(file, &log, logsize); //new way for(i = 0; < logsize; i++) { utmpprint(&log[i]); } close(file); //new way } else { return(0); } return(0); }

here of output working way:

and here output new way not working:

i have tried looking online more info on matter can't seem find uses file descriptor , not file. tried changing around of pointers , references did not improve of results.

i new c , think using read() function incorrectly in case because passing simple buffer read function when think should somehow passing utmp construction array.

you not reading plenty info file.

read(file, &log, logsize);

should be:

read(file, &log, sizeof(log)); // or read(file, &log, logsize * sizeof (struct utmp));

also, in both cases, should check homecoming value see how many bytes read.

c linux file

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -