Help with dynamic memory allocation
Code:
#include <cstdio>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int MaxHolidays = 25;
const int MaxDescLength = 40;
const char HOLIDAY_FILE[] = "holidays.txt";
struct holidayStruct {
int holidayId;
char description[MaxDescLength+1];
int month;
int day;
double cost;
};
holidayStruct *
readHoliday(FILE* holidayfile)
{
int id;
holidayStruct *holidayPtr;
holidayfile = fopen ("holidayFile.txt", "r");
if (holidayfile!=NULL) {
holidayPtr = new holidayStruct;
if (!holidayPtr) {
printf("Critical Error: Failure to allocate memory in \n");
printf("readHoliday() function.\n");
printf("Contact your holiday management program team to resolve\n");
printf("this problem.");
exit(1);
}
holidayPtr->holidayId = id;
fscanf(holidayfile, "%d %d %f" , holidayPtr->month, holidayPtr->day, holidayPtr->cost);
//fclose(inFile);
fgets(holidayPtr->description, MaxDescLength+1, holidayfile);
return (holidayPtr);
} else return NULL;
}
int
main()
{
holidayStruct *items[MaxHolidays];
int i; // general loop counter
int itemCount; // current number of items
FILE* inputFile;
inputFile = fopen(HOLIDAY_FILE, "r");
if (inputFile==NULL)
{
printf("Holiday file %s %s",(HOLIDAY_FILE) , " could not be opened." );
getchar();
exit(1);
}
//reading from the file
itemCount = 0;
while (itemCount < MaxHolidays
&&(items[itemCount] = readHoliday(inputFile)))
++itemCount;
printf("%d %s" ,itemCount, " holidays read in.\n");
This compiles, but doesn't go through the while loop. The print statement is as follows:
o holidays read in.
here is a sample input file:
20 5 10 10.50 Tony's Birthday
11 2 10 50.00 Happy Day
6 2 16 5.00 Washington's Birthday
8 3 2 25.45 Skinned knee day
9 12 10 20.01 Last day of school
Please help me!