Hi peoples...
I was wondering about an occurence i had regarding some code i was writing.
I am writing a basic library catalogue system for a uni assignment and had the following question (see code below):
after i create a array of structures, i read them in from a file. then when i add a new structure to the array from user input, it seems to tack it onto the end of the array fine, even though i havent created the necessary memory for it... i was wondering why this is happening?
code:
Code:
#define MAXLENGTH 30
// data structure:
struct book
{
char title[MAXLENGTH];
char authFirstName[MAXLENGTH];
char authSurname[MAXLENGTH];
int pubYear;
float replacementCost;
};
// open the file.
FILE *openFile(char *fileName, char mode)
{
FILE *openedFile;
openedFile = fopen(fileName, &mode);
if(openedFile == NULL)
{
printf("File '%s' not opened correctly.\n", fileName);
}else
{
printf("File '%s' opened correctly.\n", fileName);
}
return openedFile;
}
// read the contents of the file
void readFile(FILE *openedFile, struct book *bookDB, int iNumOfBooks)
{
int i;
for(i = 0; i < iNumOfBooks; i++)
{
fgetc(openedFile); // <-- picks up the last \n char to start the fgets
fgets(bookDB[i].title, MAXLENGTH, openedFile);
fscanf(openedFile, "%s", bookDB[i].authFirstName);
fscanf(openedFile, "%s", bookDB[i].authSurname);
fscanf(openedFile, "%d", &(bookDB[i].pubYear));
fscanf(openedFile, "%f", &(bookDB[i].replacementCost));
}
}
// add a new book:
int newBook(struct book *bookDB, int iNumberOfBooks)
{
printf("Adding a book to the collection...\n");
printf("Title:: ");
fgets(bookDB[iNumberOfBooks].title, MAXLENGTH, stdin);
printf("Auther firstname:: ");
scanf("%s", bookDB[iNumberOfBooks].authFirstName);
strcat(bookDB[iNumberOfBooks].authFirstName, ",");
printf("Auther Surname:: ");
scanf("%s", bookDB[iNumberOfBooks].authSurname);
printf("Year of Publication:: ");
scanf("%d", &(bookDB[iNumberOfBooks].pubYear) );
printf("Replacement Cost:: ");
scanf("%f", &(bookDB[iNumberOfBooks].replacementCost) );
iNumberOfBooks++;
return iNumberOfBooks;
}
// call to open the file, read the file and add a new book:
printf("Please enter a filename to open:: ");
scanf("%s", fileName);
openedFile = openFile(fileName, 'r'); // opens a file
fscanf(openedFile, "%d", &iNumberOfBooks); // gets the number of books from file.
bookDB = (struct book*) malloc(sizeof(struct book)*iNumberOfBooks);
readFile(openedFile, bookDB, iNumberOfBooks);
fclose(openedFile);
iNumberOfBooks = newBook(bookDB, iNumberOfBooks);
Sorry about the long windedness of the code, but i wasnt sure what you would/wouldnt be needed.
any comments would be very welcome.
Thanks!
Joel aka SoulRedemption.