Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // head.h
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- size_t current_num_tables = 0;
- const int N = 10000;
- struct table
- {
- char code[9];
- char name[255];
- int numb;
- };
- void print(struct table q[])
- {
- printf("The table looks like this:\n\n");
- printf("Product code\t Name\t Quantity\n\n");
- for (int i = 0; i < N; i++)
- {
- if (q[i].code[0] != '\0')
- {
- printf("%s\t %s\t %d\n", q[i].code, q[i].name, q[i].numb);
- }
- }
- }
- void add_table(struct table* t, const char* _code, const char* _name, const int _numb)
- {
- size_t i, index = 0;
- if (index == 0)
- {
- strcpy(t[index].code, _code);
- strcpy(t[index].name, _name);
- t[index].numb = _numb;
- index++;
- current_num_tables++;
- }
- binarysearch(_numb, t, current_num_tables);
- index = binarysearch(_numb, t, current_num_tables);
- if (t[index].numb != NULL)
- for (i = 1; i < index; i++)
- {
- memcpy(&t[i], &t[i - 1], sizeof(*t));
- }
- else
- {
- strcpy(t[index].code, _code);
- strcpy(t[index].name, _name);
- t[index].numb = _numb;
- }
- current_num_tables++;
- return;
- }
- int binarysearch(size_t a, struct table* t, size_t n)
- {
- int low, high, middle;
- low = 0;
- high = n - 1;
- while (low <= high)
- {
- middle = (low + high) / 2;
- if (a < t[middle].numb)
- high = middle - 1;
- else if (a > t[middle].numb)
- low = middle + 1;
- else
- return middle;
- }
- return -1;
- }
- //main.cpp
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <string.h>
- #include <conio.h>
- #include <Windows.h>
- #include "head.h"
- int main()
- {
- system("color 0A");
- int i;
- struct table *t;
- t = (struct table*)malloc(N * sizeof(struct table));
- for (i = 0; i < N; i++)
- {
- t[i].code[0] = '\0';
- t[i].name[0] = '\0';
- t[i].numb = 0;
- }
- FILE *f = fopen("work.txt", "r");
- int numb;
- char name[255], code[9];
- while (fscanf(f, "%s %s %i", code, name, &numb) != EOF && current_num_tables < N)
- {
- add_table(t, code, name, numb);
- }
- fclose(f);
- // bubbleSort(t, current_num_tables);
- // InsertionSort(t, current_num_tables);
- print(t);
- f = fopen("table.txt", "w");
- fprintf(f,"Product code\tName\tQuantity\n\n");
- for (i = 0; i < N; i++)
- {
- if (t[i].code[0] != '\0')
- {
- fprintf(f, "%s\t%s\t%i\n", t[i].code, t[i].name, t[i].numb);
- }
- }
- fclose(f);
- free(t);
- printf("\n\nData is written to a file. Press any key.\n\n\n\n");
- _getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement