1. A small grocery store uses a very basic file format to store prices for its goods. This file format has one item per line. The first word of the line is the name of the product, and after this is the price of the product in dollars (no dollar sign). For example, a typical file might look like:
bread $2.50
milk $1.90
pizza $10.95
Write a C program which reads one such file (create your own for testing) into two arrays,one called “items” which stores the product names, and the other called “prices” which storesall the prices. When creating the arrays, assume that the maximum length of a product name should be capped at 100 characters, and that there is a maximum of 1000 products in the file. Once all values are stored in the array, print the product list to the screen, including dollar signs in the prices as necessary along with headers for each column, for example:
ITEM PRICE
==============
bread $2.50
milk $1.90
pizza $10.95
2.
Write a C program that creates an array of 50 floating-point numbers, and assigns them the values 0, 0.5, 1, 1.5, 2, ..., 24.5. Next, write all of these numbers to a binary file called "floats.dat", using a single C statement to write the entire array at once. Note that the numbers must be written in binary form, not as text.
#include <stdio.h>
#include <stdlib.h>
struct product
{
char item[100];
float price;
};
void main()
{
int n;
struct product p[1000];
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
// Moves the cursor to the end of the file
fseek(fptr, sizeof(struct product), SEEK_SET);
for(n = 1; n < 5; ++n)
{
fread(&p, sizeof(struct product), 1, fptr);
printf("%c $%f",p->item,p->price);
fseek(fptr, 2*sizeof(struct product), SEEK_CUR);
}
fclose(fptr);
}
Get Answers For Free
Most questions answered within 1 hours.