64.9k views
0 votes
Your program this week will have the same output as lab 10, except that instead of redirecting the filename for the input file, you will get the filename from the command-line, and use a file pointer to open the file. You will also dynamically allocate space in memory after reading in the first value from the file indicating the number of lean proteins that are in the file.

User JonathanGB
by
5.7k points

1 Answer

4 votes

Answer:

Check the explanation

Step-by-step explanation:

defs.h

#ifndef DEFS_H

#define DEFS_H

#include <stdio.h>

#include <stdlib.h>

typedef struct

{

char item[20];

char quantity[10];

int calories;

float protein;

float carbs;

float fats;

} food;

int size;

void printArray(int size, food arr1[]);

#endif

arrayProcessing.c

#include "defs.h"

void printArray(int size, food arr1[])

{

int i = 0;

printf("\\FOOD ITEM\t\tQUANTITY\tCALS\tPRO\tCARBS\tFAT");

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

{

printf("\\%i.%s", i + 1, arr1[i].item);

printf("\t\t%s", arr1[i].quantity);

printf("\t\t%i", arr1[i].calories);

printf("\t%.2f", arr1[i].protein);

printf("\t%.2f", arr1[i].carbs);

printf("\t%.2f\\", arr1[i].fats);

}

}

lab12.c

#include "defs.h"

int main(int argc, char *argv[])

{

int i = 0;

FILE *inFile;

inFile = fopen(argv[1], "r");

if(inFile==NULL){

fprintf(stderr, "File open error. Exiting program\\");

exit(1);

}

fscanf(inFile, "%i", &size);

food *arr = (food *)malloc(sizeof(food)*size);

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

{

fscanf(inFile, "\\%[^\\]s", arr[i].item);

fscanf(inFile, "%s", arr[i].quantity);

fscanf(inFile, "%i", &arr[i].calories);

fscanf(inFile, "%f", &arr[i].protein);

fscanf(inFile, "%f", &arr[i].carbs);

fscanf(inFile, "%f", &arr[i].fats);

}

printArray(size, arr);

return 0;

}

Kindly check the Output below,

Your program this week will have the same output as lab 10, except that instead of-example-1
User Antacerod
by
6.2k points