I'm wondering if anyone can help me with my below code. I'm struggling to implement dynamic allocation for my program when reading data from a file and storing it in a struct. I'm new to both structs and dynamic allocation. While my program seems to be storing the data successfully into the struct I can see in Visual Studio that the allocation of these is not correct. Any advice on storing the data dynamic would be much appreciated. I was trying to use malloc but could not get this to work for me.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void load_data();
typedef struct {
char name[12];
char vaccinevendor[8];
char vaccinationdate[12];
char dob[12];
char underlyingcond[8];
char id[7];
} Record;
int main(void)
{
load_data();
return 0;
}
void load_data()
{
Record s1[2];
FILE* Ptr; /*file pointer*/
if ((Ptr = fopen("records.txt", "rb")) == NULL) {
printf("File does not exist\n");
Ptr = fopen("records.txt", "w");
if (Ptr != NULL)
printf("records.txt file has now been created.\n");
else {
printf("Unable to create file!\n");
return 1;
}
}
Ptr = (char*)malloc(1000 * sizeof(char));
// read file contents till end of file
fread(&s1, sizeof(Record), 2, Ptr);
fclose(Ptr); /*close stream*/
}
Hi all,
As per my comment below I have updated my code but am getting errors when trying to store my array strings into my struct. As I was asked in the comments also, the test file contents are lines in the following format:
John Smith
Pfizer
02/08/2021
06/01/1990
None
556679
Mary Jones
None
None
09/10/1988
Asthma
556677
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 13
#define stringlen 15
#define numoflines 12
void load_data();
typedef struct {
char name[12];
char vaccinevendor[8];
char vaccinationdate[12];
char dob[12];
char underlyingcond[8];
char id[7];
} Record;
int main(void)
{
load_data();
return 0;
}
void load_data()
{
char line[110], buff[13][50];
int len;
int i = 0;
Record s1[2];
FILE* Ptr; /*file pointer*/
if ((Ptr = fopen("records.txt", "rb")) == NULL) {
printf("File does not exist\n");
Ptr = fopen("records.txt", "w");
if (Ptr != NULL)
printf("records.txt file has now been created.\n");
else {
printf("Unable to create file!\n");
return 1;
}
}
for (i = 0; i < SIZE; ++i)
{
len = strlen(buff[i]);
fgets(buff[i], 21, Ptr);
s1[0] = malloc(len);
strcpy(s1[i], buff);
}
fclose(Ptr); /*close stream*/
}
voidfunction should notreturna return value...Ptr = (char*)malloc(1000 * sizeof(char));.Ptris not of typechar *. You should create a new varaible for this. You also can't close a char pointer.freadis wrong. This SO question deals with that problem.return 1;"warning: assignment to 'FILE *' from incompatible pointer type 'char *' [-Wincompatible-pointer-types]"Ptr = (char*) malloc(1000 * sizeof(char));