What is wrong with this program?

Andrew Koenig ark at alice.UUCP
Sat Aug 10 14:40:55 AEST 1985


> #include <stdio.h>

> main()
> {

>	struct utmp {    /* This structure is straight out of utmp.h */
>		char	ut_line[8];		/* tty name */
>		char	ut_name[8];		/* user id */
>		long	ut_time;		/* time on */
>	};

>	FILE *f;
>	int i;
>	struct utmp *data;
>	if (f = fopen ("/usr/adm/wtmp", "r")) {
>		while ((fread (data, sizeof(struct utmp), 1, f))  >  0) {
>			putchar('\t');
>			for (i = 0; i <= 7; i++) {
>				putchar(data->ut_line[i]);
>			}
>			printf("\n");
>			printf("%s	%s	%ld\n", data->ut_name,
>				data->ut_line, data->ut_time);
>		}
>		fclose(f);
>	}
> }

When you are reading into the thing pointed to by data,
data doesn't point anywhere because you've never initialized it!
Change the declaration of data:

	struct utmp data;

and every place you now use data, use its address instead:

	while ((fread (&data, sizeof(struct utmp), 1, f)) > 0) {
		...
			putchar (data.ut_line[i]);
		...

		printf ("%.8s      %.8s      %ld\n", data.ut_name,
			data.ut_line, data.ut_time);
		...

Also notice the %.8s -- this defends against the field being
completely full.  In that case it would not have a null terminator.



More information about the Comp.lang.c mailing list