Brood Brood - 3 years ago 133
C Question

Write function that accepts pointer variables and and assigns values from file to struct in C

I have a text file that looks like this:

Temba Bavuma 10.05 Hashim Amla 5.04Dale Steyn 16.78

I am given a struct in separate header file that looks like:


struct apartmentData
char ownerName[30];
char ownerSurname[30];
double tariff;
typedef struct apartmentData ApartmentData;


I have to use the following function to assign three different apartments the values from the text file and the function should not produce output:

void readMetadataFromFile(ApartmentData *data1, ApartmentData *data2, ApartmentData *data3);

The apartments are assigned their values through this function in my main.c. There is a different header file for the function and the apartment struct. The function has its 'own' .c file.

I am not sure how to add the values to the different apartments. I understand how to open a file and read in the values. I do not understand how to assign three apartments their appropriate values through a function with this struct and pointer. I have to use this function prototype as is. Can someone please help?

Answer Source

If you just want to read from the text file into the ApartmentData variables using the void readMetadataFromFile(ApartmentData *data1, ApartmentData *data2, ApartmentData *data3); function you could do

void readMetadataFromFile(ApartmentData *data1, ApartmentData *data2, ApartmentData *data3)
    FILE *fin=fopen("apartment.txt", "r");
    fscanf(fin, "%29s %29s %lf", data1->ownerName, data1->ownerSurname, &data1->tariff);
    printf("\n\n%s %s %lf", data1->ownerName, data1->ownerSurname, data1->tariff);

    fscanf(fin, "%29s %29s %lf", data2->ownerName, data2->ownerSurname, &data2->tariff);
    printf("\n\n%s %s %lf", data2->ownerName, data2->ownerSurname, data2->tariff);

    fscanf(fin, "%29s %29s %lf", data3->ownerName, data3->ownerSurname, &data3->tariff);
    printf("\n\n%s %s %lf", data3->ownerName, data3->ownerSurname, data3->tariff);


You should also check the return value of the fscanf() to see if the assignments were successful.

In this case, each of the fscanf()s should return 3 which is the number of successful assignments. If it isn't 3 some error has occurred.

The -> operator is used to access the contents of a struct via a pointer to it.

Edit: chux pointed out that there are chances of overflow with fscanf().

Since the sizes of the string members of the structure is 30, use "%29s" while reading into them allowing for the \0 character denoting the end of string.

Otherwise if a string of size greater than that of the character array is supplied, memory out of bounds of array will be overwritten, invoking undefined behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download