Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- // ex 1
- struct IceCream{
- char id[3];
- char name[21];
- int weight;
- float price;
- };
- int main() {
- printf("Enter n:\n ");
- int n;
- scanf("%d", &n);
- if (n < 5 || n > 15) {
- printf("Wrong input\n");
- return 1;
- }
- struct IceCream* iceCream = (struct IceCream*)malloc(n*sizeof(struct IceCream));
- if (iceCream == NULL) {
- printf("Memory allocation error\n");
- return 1;
- }
- for (int i = 0; i < n; i++) {
- printf("Enter id:\n ");
- scanf("%s", iceCream[i].id);
- printf("Enter name:\n ");
- scanf("%s", iceCream[i].name);
- printf("Enter weight:\n ");
- scanf("%d", &iceCream[i].weight);
- printf("Enter price:\n ");
- scanf("%f", &iceCream[i].price);
- }
- return 0;
- }
- // ex 2
- float sum(struct IceCream* iceCream, int n, char letter) {
- float sum = 0;
- for (int i = 0; i < n; i++) {
- if (iceCream[i].name[0] == letter) {
- sum += iceCream[i].price;
- }
- }
- if(sum > 0){
- return sum;
- }
- return 0;
- }
- // ex 3
- int write(struct IceCream* iceCream, int n, float price, int weight) {
- FILE *file = fopen("info.txt", "w");
- if (file == NULL) {
- printf("File could not be opened\n");
- return 1;
- }
- int counter = 0;
- for (int i = 0; i < n; i++) {
- if (iceCream[i].price < price && iceCream[i].weight > weight) {
- counter++;
- fprintf(file, "%s; %s; %d; %.2fлв\n", iceCream[i].id, iceCream[i].name, iceCream[i].weight, iceCream[i].price);
- }
- }
- fclose(file);
- free(iceCream);
- if (counter > 0) {
- return counter;
- }
- return 0;
- }
- struct binary{
- char id[3];
- int nameLength;
- char name[100];
- int weight;
- float price;
- };
- //ex 4
- int info(char id[3]) {
- FILE *file = fopen("icecream.bin", "rb");
- if (file == NULL) {
- printf("File could not be opened\n");
- return 1;
- }
- if (fseek(file, 0, SEEK_END) != 0) {
- printf("File could not be seeked\n");
- fclose(file);
- return 1;
- }
- long size = ftell(file);
- if (size < 0) {
- printf("Error determining file size\n");
- fclose(file);
- return 1;
- }
- rewind(file);
- int n = size/sizeof(struct binary);
- struct binary* info = (struct binary*)malloc(n*sizeof(struct binary));
- if (info == NULL) {
- printf("Memory could not be allocated\n");
- fclose(file);
- return 1;
- }
- if (fread(info, sizeof(struct binary), n, file) != n) {
- if (feof(file)) {
- printf("File could not be read\n");
- } else if (feof(file)) {
- printf("Error determining file size\n");
- }
- fclose(file);
- free(info);
- return 1;
- }
- int find = -1;
- for (int i = 0; i < n; i++) {
- if (strcmp(info[i].id, id) == 0) {
- find = i;
- }
- }
- if (find != -1) {
- printf("%s - %s - %d - %.2f", info[find].name, info[find].id, info[find].weight, info[find].price);
- }
- else{
- printf("IceCream does not exist\n");
- }
- fclose(file);
- free(info);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement