Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
char *vector(char friends[], int *length) {
char *temp;
temp = calloc(*length+10, sizeof(char)); // Make new dynamic array.
memcpy(temp, friends, *length); // Copy data to new array.
*length+=10; // Increment & record new length.
free(friends); // Free old array.
return temp; // Return new array.
}
int main(void) {
struct list {
char IDP[3];
char first[42];
char last[42];
char phone[42];
} *friends;
char friendArray;
int i, j, k, l, count;
int base = 10;
char IDP[3], first[42], last[42], phone[42];
FILE *data;
//Determine size of data files
data = fopen("./hw4.data", "r");
count = 0;
while (1) {
fscanf(data, "%s %s %s %s", IDP, first, last, phone);
if (feof(data)) break;
count++;
}
//Create dynamic array of structures
friends = (struct list *)calloc(base, sizeof(struct list));
// Populate dynamic array, deleting and printing where necessary
rewind(data);
j = 0;
printf("%d\n", count);
for (i = 0; i < count; i++) {
if (friends[i].IDP == "I") { //Add line to dynamic array
fscanf(data, "%s %s %s %s", friends[i].IDP, friends[i].first, friends[i].last, friends[i].phone);
}
else if (friends[i].IDP == "D") { //Delete line from dynamic array
//Find and delete friend
}
else if (friends[i].IDP == "P") { //Print entire array
for (k = 0; k < count; k++) {
printf("%s %s %s %s\n", friends[i].IDP, friends[i].first, friends[i].last, friends[i].phone);
}
}
/*j++;
if (j == 10) {
j = 0;
friends = vector(friends, &base); // Adjust vector length
}*/
}
fclose(data);
free(friends);
return 0;
}
Data File:
Code:
I Steve Marsh 701-222-3333
I Dave Marsh 218-444-6666
I Radell Marsh 701-235-8133
I Brenda Marsh 701-277-5050
I Kia Marsh 701-275-1234
I Triston Marsh 701-275-0987
P
The issue I'm having is it doesn't seem to be printing the structure array when it reads in the last line. My program compiles and runs; it just doesn't print the array when it gets to the "P" in the data file. Is the comparison
Code:
friends[i].IDP == "I"
correct or am I doing something wrong?
Also, I'm having an issue importing the friends array into the array re-size function (vector, hence why that section is commented out) but I want to solve this problem first.