[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here

Example on using Structs and Files together

Created: Wednesday, 08 January 2014 Written by Ehab Eldeeb

Assume that a file shoes.txt, contains information about shoes in a shoe store.

A shoe is represented in the file by its size, color, price, and manufacturer's name.

Use a struct to represent shoes, then write a program that does the following:

  1. Store the information of all shoes with size above 50 in large.txt
  2. Store the information of all shoes with above average price in expensive.txt
  3. Calculate the average price of RED shoes

This is a really long program for an exam, if you don't get the idea as fast, you won't be able to solve it .. But let's do it now :)

Programming Applications 15/1/2013 Final Exam

#include <stdio.h>
#include <conio.h>
#include <string.h>

typedef struct {
    int size;
    char color[20];
    float price;
    char manuf[50];
} shoe;

int main(){
    shoe shoes[20000];
    float avgprice = 0, redavg = 0;
    int redno = 0;

    // Read the file shoes.txt
    FILE *p;
    p = fopen("shoes.txt", "r");
    int i = 0; // global counter
    while (feof(p) == 0){
        fscanf(p, "%d%s%f%s", &shoes[i].size, shoes[i].color, &shoes[i].price, shoes[i].manuf); // strings won't need &
        i++;
    }
    fclose(p);

    // Get info about shoes with size above 50 in another file large.txt
    FILE *large;
    large = fopen("large.txt", "w");
    for(int j = 0; j < i; j++){
        if (shoes[i].size > 50)
            fprintf(large, "%d%s%f%s", shoes[j].size, shoes[j].color, shoes[j].price, shoes[j].manuf);
    }
    fclose(large);

    // Once again, store shoes with prices above the average in file expensive.txt
    for(int a = 0; a < i; a++){
        avgprice += shoes[a].price; // Sum of all prices
    }
    avgprice /= i; // divide the total sum over the number of shoes

    FILE *expensive;
    expensive = fopen("expensive.txt", "w");
    for (int b = 0; b < i; b++){
        if (shoes[b].price > avgprice)
            fprintf(expensive, "%d%s%f%s", shoes[b].size, shoes[b].color, shoes[b].price, shoes[b].manuf);
    }
    fclose(expensive);

    // Calculate average price for red shoes
    for(int x = 0; x < i; x++){
        if(strcmp(shoes[x].color, "red") == 0){
            redavg += shoes[x].price;
            redno++;
        }
    }
    redavg /= redno;
    printf("Average price of red shoes is %f", redavg);
    getch();
}

Note: This program was written quickly in a few minutes, and it hasn't been tested.
If you found any errors, your comments are appreciated.