Примеры программ к Лабораторной работе N8. "Структуры данных"

/* booksave.c - сохранение содержимого структуры в файле */
#include <stdio.h>
#include <stdlib.h>

#define MAXTITL	40
#define MAXAUTL	40
#define MAXBKS 10		/* максимальное количество книг */

struct book {			/* создание шаблона book */
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
};

int main(void)
{
	struct book library[MAXBKS];	/* массив структур */
	int count = 0;
	int index, filecount;
	FILE * pbooks;
	int size = sizeof (struct book);

	if ((pbooks = fopen("book.dat", "a+b")) == NULL) {
		fputs("He удается открыть файл book.dat\n",stderr);
		exit(1);
	}
	rewind(pbooks); /* переход в начало файла */
	while (count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1) {
		if (count == 0)
			puts("Текущее содержимое файла book.dat:");
		printf("%s by %s: $%.2f\n",library[count].title, library[count].author, library[count].value);
		count++;
	}
	filecount = count;
	if (count == MAXBKS) {
		fputs("Файл book.dat заполнен.", stderr);
		exit(2);
	}

	puts("Введите названия новых книг.");
	puts("Нажмите [enter] в начале строки для выхода из программы.");
	
	while (count < MAXBKS && gets(library[count].title) != NULL	&& library[count].title[0] != '\0') {
		puts("Teпepь введите имя автора.");
		gets(library[count].author);
		puts("Teпepь введите цену книги.");
		scanf ("%f", &library[count++].value);
		while (getchar() != '\n')
			continue;	/* очистить входную строку */
		if (count < MAXBKS)
			puts("Введите название следующей книги.");
	}

	if (count > 0) {
		puts("Каталог ваших книг:");
		for (index = 0; index < count; index++)
			printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
			fwrite(&library[filecount], size, count - filecount, pbooks);
	}
	else
		puts("Вообще нет книг? Очень плохо.\n");
	
	puts("Bcero доброго.\n") ;
	fclose(pbooks);

	return 0;
}
// friend.c - пример вложенной структуры
#include <stdio.h>
#define LEN 40

const char * msgs[5] =
{
"Благодарю вас за чудесно проведенный вечер, ",
"Вы однозначно продемонстрировали, что ",
"являет собою особый тип личности. Мы обязательно должны встретиться", "за восхитительным ужином с ",
" и весело провести время."
};

struct names {	// первая структура
	char first[LEN];
	char last[LEN];
};

struct guy {				// вторая структура
	struct names handle;	// вложенная структура
	char favfood[LEN];
	char job [LEN];
	float income;
};

int main(void){
	struct guy fellow = {	// инициализация переменной
		{ "Стивен", "Кинг" },
		"запеченными омарами",
		"известный писатель",
		58112.00
	};
	
	printf("Дорогой %s, \n\n", fellow.handle.first) ;
	printf("%s%s.\n", msgs[0], fellow.handle.first);
	printf("%s%s\n", msgs[1], fellow.job);
	printf("%s\n", msgs[2]);
	printf("%s%s%s", msgs[3], fellow.favfood, msgs[4]);
	if (fellow.income > 150000.0)
		puts("!!");
	else if (fellow.income > 75000.0)
		puts("!");
	else
		puts(".");
	printf("\n%40s%s\n", " ", "До скорой встречи,");
	printf("%40s%s\n", " ", "Шейла");
	
	return 0;
}
/* friends.с - использование указателя на структуру */
#include <stdio.h>

#define LEN 50

struct names {
	char first[LEN];
	char last[LEN];
};

struct guy {
	struct names handle;
	char favfood[LEN];
	char job[LEN];
	float income;
};

int main(void) {
	struct guy fellow[2] = {
		{{"Стивен", "Кинг"},
		"запеченными омарами",
		"персональный тренер",
		58112.00
		},

		{{"Родни", "Стюарт"},
		"рыбным фрикасе",
		"редактор таблоида",
		232400.00
		}
	};

	struct guy * him;	/* указатель на структуру */
	printf("адрес #1: %p #2: %p\n", &fellow[0], &fellow[1]);
	him = &fellow[0];	/* говорит указателю, на что указывать */
	printf("указатель #1: %p #2: %p\n", him, him + 1);
	printf("him->income равно $%.2f: (*him).income равно $%.2f\n", him->income, (*him).income);
	him++;	/* указатель на следующую структуру */
	printf("him->favfood равно %s: him->handle.last равно %s\n", him->favfood, him->handle.last);
	return 0;
	
}
/* funds4.c - передача функции массива структур */
#include <stdio.h>

#define FUNDLEN 50
#define N 2

struct funds {
	char bank[FUNDLEN];
	double bankfund;
	char save[FUNDLEN];
	double savefund;
};

double sum(const struct funds money[], int n);

int main(void)
{
	struct funds jones[N] = {
		{
			"Garlic-Melon Bank",
			3024.72,
			"Lucky's Savings and Loan",
			9237.11
		},
		{
			"Honest Jack's Bank",
			3534.28,
			"Party Time Savings",
			3203.89
		}
	};

	printf("Семейство Джонсов имеет на счету общую сумму в $%.2f.\n", sum(jones,N));

	return 0;

}

double sum(const struct funds money[], int n) {
	double total;
	int i;
	
	for (i = 0, total = 0; i < n; i++)
		total += money[i].bankfund + money[i].savefund;
	return(total);
}