Вы находитесь на странице: 1из 30

Министерство Образования и Исследований 

Республики Молдова 
 
Технический Университет Молдовы 
 
Кафедра «Автоматика и информационные технологии»
              
 
 
 
Отчет 
по лабораторной работе Nr.6-7. 
по Структурам Данных и Алгоритмам

Тема: Обработка массива структур и использование файлов


на языке Си
 
                                         Вариант 5  
 
 
 
 

 
Выполнил ст.гр. SI-                         
 
Проверила                                                   

                              Кишинев – 202X

1
Лабораторная работа Nr.6. 
Тема работы: Обработка массива структур и использование файлов на языке Си

Цель работы: Программирование алгоритмов для обработки массива структур, используя


функции, указатели, динамическое выделение памяти и файлы на языке Си.

Задание:
1. Для заданного массива элементов типа структура (Структура ТОВАР с полями: название,
страна, производитель, артикул, цена.) вывести на экран следующее меню операций:

1. Динамическое выделение памяти для массива структур.


2. Ввод элементов массива с клавиатуры.
3. Поиск элемента массива.
4. Сортировка массива.
5. Редактирование элемента массива.
6. Добавление нового элемента в конец.
7. Удаление указанного элемента из массива.
8. Вставка нового элемента.
9. Запись элементов массива в файл.
10. Считывание элементов массива из файла.
11. Вывод элементов массива на экран.
12. Освобождение памяти, выделенной для массива.
13. Окончание работы программы.

Реализовать функции, обеспечивающие операции меню.

Мой код:
___________________________________main.cpp_________________________________________

#include "head.h"

int main()

int N;

int choice;

struct good *g = NULL;

printf ("\nMenu:\n");
2
printf ("1.Dynamic memory allocation for a array of struct;\n");

printf ("2.Enter array elements from the keyboard;\n");

printf ("3.Writing an array of structures to a file .txt;\n");

printf ("4.Reading an array of structures from a file .txt;\n");

printf ("5.Display array elements on the screen;\n");

printf ("6.Sort array elements;\n");

printf ("7.Search for an array element;\n");

printf ("8.Adding a new element to the end;\n");

printf ("9.Editing an array element;\n");

printf ("10.Insert a new element;\n");

printf ("11.Reading an array of structures from a file .txt;\n");

printf ("12.DeleteMemoryArray;\n");

printf ("13.End of the program;\n");

do

printf ("\n\nChoose a number from the menu: ");

scanf ("%d", &choice);

switch(choice) // Execution of functions according to user choice

//1 Dynamic memory allocation for a array of struct

case 1:

MemoryAllocationArray( g, N);

printf ("\n address g = %x, value of g = %p", &g, g);

break;

//2 Enter array elements from the keyboard

case 2:

3
EnterElementsArray(g, N);

break;

//3 Writing an array of structures to a file .txt

case 3:

WriteFileElementsArray(g, N);

break;

//4 Reading an array of structures from a file .txt

case 4:

ReadFileElementsArray(g, N);

break;

//5 Display array elements on the screen

case 5:

PrintScreenElementsArray(g, N);

break;

//6 Sort array elements

case 6:

SortElementsArrayByName(g, N);

break;

//7 Search for an array element

case 7:

SearchElementsArray(g, N);

break;

//8 Adding a new element to the end

case 8:

AddEndElementsArray(g, N);

break;

//9 Editing an array element

case 9:

4
EditElementsArray(g, N);

break;

//10 Insert a new element

case 10:

InsertElementsArray(g, N);

break;

//11 Removing the specified element from the array

case 11:

RemoveElementsArray(g, N);

break;

//12 DeleteMemoryArray

case 12:

DeleteMemoryArray(g);

break;

//13 End of the program

case 13:

if(g != NULL) DeleteMemoryArray(g);

printf("\n Successful exit from the program!\n");

return 0;

default:

printf ("\nInvalid input. Select a number from the menu.");

break;

} while (choice <13);

getch();

return 0;

5
_______________________________head.h______________________________________________

#include <stdio.h>

#include <stdlib.h>

#include <iostream>

#include <limits>

#include <string.h>

#include <conio.h>

#include <time.h>

#include <math.h>

struct good

char name[50];

char country[50];

char manufacturer[50];

int vendorcode;

int price;

};

void MemoryAllocationArray(struct good *&g, int &R);

void DeleteMemoryArray(struct good *&g);

int EnterElementsArray(struct good *g, int R);

int PrintScreenElementsArray(struct good *g, int R);

int WriteFileElementsArray(struct good* g, int R);

int ReadFileElementsArray(struct good* g, int R);

6
int SortElementsArrayByName(struct good* g, int R);

int SearchElementsArray(struct good* g, int R);

int AddEndElementsArray(struct good* g, int R);

int EditElementsArray(struct good* g, int R);

int RemoveElementsArray(struct good* g, int R);

int InsertElementsArray(struct good* g, int R);

void DeleteElementsArray(struct good* g);

___________________________________func.cpp__________________________________________

#include "head.h"

int adding=0;

//1 Dynamic memory allocation for array of struct

void MemoryAllocationArray(struct good *&g, int &R)

printf("\n Input size of array:");

scanf("%d", &R);

g = new good[R];

if ( g == NULL)

printf("\n dynamic memory is not allocated for an array of structures ");

exit(1);

else

printf("\n allocated memory:%d bytes", R*sizeof(good));

7
}

//2 Enter array elements from the keyboard

int EnterElementsArray(struct good* g, int R)

int i;

for ( i = 0; i < R; i++)

fflush (stdin);

printf("\n Input good's name:\n");

gets(g[i].name);

fflush (stdin);

printf("\n Input country:\n");

gets(g[i].country);

fflush (stdin);

printf("\n Input manufacturer:\n");

gets(g[i].manufacturer);

printf("\n Input vendor code:\n");

scanf("%d", &g[i].vendorcode);

printf("\n Input price:\n");

scanf("%d", &g[i].price);

return 0;

//3 Writing an array of structures to a file .txt

8
int WriteFileElementsArray(struct good* g, int R)

int i;

FILE *fp;

fp = fopen("goods.txt", "w");

for ( i = 0; i < R; i++)

fprintf(fp, "%s %s %s %d %d\n",

g[i].name, g[i].country, g[i].manufacturer, g[i].vendorcode, g[i].price);

fclose ( fp );

return 0;

//4 Reading an array of structures from a file .txt

int ReadFileElementsArray(struct good* g, int R)

int i;

FILE *fp;

fp = fopen("goods.txt", "r");

for ( i = 0; i < R; i++ )

fscanf(fp, "%s %s %s %d %d\n",

9
&g[i].name, &g[i].country, &g[i].manufacturer, &g[i].vendorcode, &g[i].price);

fclose ( fp );

return 0;

//5 Display array elements on the screen

int PrintScreenElementsArray(struct good* g, int R)

int i;

printf(" -------------------------------------------------------------------------------------------------------\n");

printf(" | # | Name | Country | Manufacturer | Vendor code | Price |\n");

printf(" -------------------------------------------------------------------------------------------------------\n");

for ( i = 0; i < (R+adding); i++)

printf(" | %d |%-12s |%-14s |%-12s |%5d |%5d | \n", i+1, g[i].name,g[i].country,


g[i].manufacturer, g[i].vendorcode,g[i].price);

printf(" -------------------------------------------------------------------------------------------------------\n");

return 0;

//6 Sort array elements

int SortElementsArrayByName(struct good* g, int R)

10
printf("\nEnter the criterium you would like to sort by:\n");

printf("\n1.Sort by name:\n");

printf("\n2.Sort by country:\n");

printf("\n3.Sort by manufacturer:\n");

printf("\n4.Sort by vendor code:\n");

printf("\n5.Sort by price in ascending order:\n");

printf("\n6.Sort by price in descending order:\n");

int i,j;

struct good temp;

int criterium;

printf ("\n\n>");

scanf("%d", &criterium);

switch(criterium)

case 1:

for (i=0;i<(R+adding)-1;i++)

for (j=i+1; j<(R+adding); j++)

if (strcmp(g[i].name, g[j].name) >0)

temp= g[i];

g[i]=g[j];

g[j]=temp;

11
}

break;

case 2:

for (i=0;i<(R+adding)-1;i++)

for (j=i+1; j<(R+adding); j++)

if (strcmp(g[i].country, g[j].country) >0)

temp= g[i];

g[i]=g[j];

g[j]=temp;

break;

case 3:

for (i=0;i<(R+adding)-1;i++)

for (j=i+1; j<(R+adding); j++)

if (strcmp(g[i].manufacturer, g[j].manufacturer) >0)

12
temp= g[i];

g[i]=g[j];

g[j]=temp;

break;

case 4:

for (i=0;i<(R+adding)-1;i++)

for (j=i+1; j<(R+adding); j++)

if (g[i].vendorcode < g[j].vendorcode)

temp= g[i];

g[i]=g[j];

g[j]=temp;

break;

case 5:

for (i=0;i<(R+adding)-1;i++)

for (j=i+1; j<(R+adding); j++)

13
if (g[i].price > g[j].vendorcode)

temp= g[i];

g[i]=g[j];

g[j]=temp;

break;

case 6:

for (i=0;i<(R+adding)-1;i++)

for (j=i+1; j<(R+adding); j++)

if (g[i].price < g[j].price)

temp= g[i];

g[i]=g[j];

g[j]=temp;

break;

defaul:

printf ("\n\nError please enter a valid value ");

break;

14
}

return 0;

//7 Search for an array element

int SearchElementsArray(struct good* g, int R)

char search[50];

int criterium2;

int value;

int result;

printf ("\n\nEnter the criterium you would like to search with:\n");

printf("\n1.Search by name\n");

printf ("\n2.Search by country\n");

printf ("\n3.Search by manufacturer\n");

printf ("\n4.Search by vendor code\n");

printf ("\n5.Search by price\n");

printf ("\n\n>");

scanf("%d", &criterium2);

switch (criterium2)

case 1:

fflush(stdin);

printf ("\nEnter the name of the good you're looking for:\n");

gets(search);

15
for (int i=0; i<(R+adding); i++)

result= strcmp(search, g[i].name);

if (result==0)

printf ("\nThe found good is:\n");

printf ("\n|%-12s|%-14s |%-12s | %5d | %5d | \n", g[i].name,g[i].country,


g[i].manufacturer,g[i].vendorcode, g[i].price);

break;

case 2:

fflush(stdin);

printf ("\nEnter the country of the good you're looking for:\n");

gets(search);

for (int i=0; i<(R+adding); i++)

result= strcmp(search, g[i].country);

if (result==0)

printf ("\nThe found good is:\n");

printf ("\n|%-12s|%-14s |%-12s | %5d | %5d | \n", g[i].name,g[i].country,


g[i].manufacturer,g[i].vendorcode, g[i].price);

16
}

break;

case 3:

fflush(stdin);

printf ("\nEnter the manufacturer of the good you're looking for:\n");

gets(search);

for (int i=0; i<(R+adding); i++)

result= strcmp(search, g[i].manufacturer);

if (result==0)

printf ("\nThe found good is:\n");

printf ("\n|%-12s|%-14s |%-12s | %5d | %5d | \n", g[i].name,g[i].country,


g[i].manufacturer,g[i].vendorcode, g[i].price);

break;

case 4:

printf ("\nEnter the vendor code of the good you're looking for:\n");

scanf ("%d", &value);

for (int i=0; i<(R+adding); i++)


17
if (value==g[i].vendorcode)

printf ("\nThe found good is:\n");

printf ("\n|%-12s|%-14s |%-12s | %5d | %5d | \n", g[i].name,g[i].country,


g[i].manufacturer,g[i].vendorcode, g[i].price);

break;

case 5:

printf ("\nEnter the price of the good you're looking for:\n");

scanf ("%d", &value);

for (int i=0; i<(R+adding); i++)

if (value==g[i].price)

printf ("\nThe found good is:\n");

printf ("\n|%-12s|%-14s |%-12s | %5d | %5d | \n", g[i].name,g[i].country,


g[i].manufacturer,g[i].vendorcode, g[i].price);

break;

default:

printf ("\n\nError. Please enter a valid value\n");

return 0;

int AddEndElementsArray(struct good* g, int R)

18
{

printf("\n Adding a new element to the end \n\n");

// allocate more memory for new object

adding++;

g = (struct good *) realloc (g, R * sizeof(struct good));

printf("\nWriting new element in the end (index: %d):", R+1);

fflush(stdin);

printf("\n Input good's name:\n");

gets(g[adding+1].name);

fflush(stdin);

printf("\n Input country:");

gets(g[adding+1].country);

fflush(stdin);

printf("\n Input manufacturer:");

gets(g[adding+1].manufacturer);

printf("\n Input vendor code:");

scanf("%d", &g[adding+1].vendorcode);

19
printf("\n Input good's price:");

scanf("%d", &g[adding+1].price);

return 0;

//9 Editing an array element

int EditElementsArray(struct good* g, int R)

printf("\n Editting of the element \n\n");

int index;

printf ("\nEnter the index of the element you would like to edit:\n>");

scanf ("%d", &index);

index--;

printf ("\nChoose the option you would like to change:\n");

printf ("1.Name\n");

printf ("2.Country\n");

printf ("3.Manufacturer\n");

printf ("4.Vendor coder\n");

printf ("5.Price\n");

int option;

scanf ("%d", &option);

switch(option)

20
{

case 1:

fflush(stdin);

printf ("Input the name you would like to set instead: \n>");

gets(g[index].name);

break;

case 2:

fflush(stdin);

printf ("Input the country you would like to set instead: \n>");

gets(g[index].country);

break;

case 3:

fflush(stdin);

printf ("Input the manufacturer you would like to set instead: \n>");

gets(g[index].manufacturer);

break;

case 4:

printf ("Input the vendor code you would like to set instead: \n>");

scanf ("%d", &g[index].vendorcode);

break;

case 5:

printf ("Input the price you would like to set instead: \n>");

scanf ("%d", &g[index].price);

break;

21
default:

printf ("\nPlease enter a valid option");

//10 Insert a new element

int InsertElementsArray(struct good* g, int R)

printf ("\nEnter the index of the element after which you would like to insert an element:\n\n");

int i;

scanf ("%d", &i);

if (i>R)

printf ("\nError. Please enter a valid index.");

return 0;

g= (struct good *) realloc (g, R *sizeof(struct good));

adding++;

for (int j=(R+adding); j>i; j--)

g[j]=g[j-1];

22
fflush(stdin);

printf("\n Input good's name:\n");

gets(g[i].name);

fflush(stdin);

printf("\n Input country:");

gets(g[i].country);

fflush(stdin);

printf("\n Input manufacturer:");

gets(g[i].manufacturer);

printf("\n Input vendor code:");

scanf("%d", &g[i].vendorcode);

printf("\n Input good's price:");

scanf("%d", &g[i].price);

printf ("\nThe element has been added sucessfully\n");

return 0;

//11 Removing the specified element from the array

int RemoveElementsArray(struct good* g, int R)

23
{

printf ("\nEnter the index of the element you would like to remove:\n\n");

int i;

scanf ("%d", &i);

if (i>R)

printf ("\nError. Please enter a valid index.");

return 0;

for (int j=i-1; j<(R+adding)-1; j++)

g[j]=g[j+1];

g= (struct good *) realloc (g, R *sizeof(struct good));

adding--;

printf ("\nThe chosen element has been removed sucessfully\n");

return 0;

//12 DeleteMemoryArray

void DeleteMemoryArray(struct good *&g)

if( g != NULL)

24
{

delete[] g;

g = NULL;

printf(" \n %p Memory freed", g);

Пример работы программы:

25
26
27
28
29
Вывод:
В ходе лабораторной работы номер 6-7 “Обработка массива структур и использование файлов на
языке Си” познакомилась с понятием структура и обучилась с ней взаимодействовать. Научилась
создавать динамические массивы структур, и производить различные операции с ними: вставка,
удаление, изменение полей, чтение/запись в файл, изменение полей структуры, поиск по
опредленому полю и сортировку. Свою программу я создавала посредством проекта из 3
файлов(основного, заголовочного и файла с реализацией функций).
30

Вам также может понравиться