Steve Lacy
Steve Lacy

Reputation: 15

Trying to write multiple lines to a file from a struct in C

i'm writing a small program thats outputs student data to text file, I store this data in a struct array, then i try to output this data to a text file; But for some reason it only outputs the most recent inputted data.

struct students
{
    char *familyName[20], *firstName[20];
    int enrolNum, mark1, mark2, mark3;
} st[1000];

FILE *fptr;
int studentNum;
int i = 0;
void main()
{
    double markOne, markTwo, markThree;

    markOne = st[i].mark1 * 0.30;
    markTwo = st[i].mark2 * 0.40;
    markThree = st[i].mark3 * 0.30;
    char *fName;
    do
    {
        ptr = fopen("student.txt", "a+");
        fprintf(fptr, "Family name \tFirst name \tenrolment number \tartefact mark 1 \tartefact mark 2 \tartefact mark 3 \n");
        fprintf(fptr,"%s \t\t%s \t\t%d \t\t\t%.1f%% \t\t%.1f%%  \t\t%.1f%% \n", st[i].familyName, st[i].firstName, st[i].enrolNum, markOne, markTwo, markThree);
        printf("\n%d\n%d", i, studentNum);
    } while( i < studentNum);
    fclose(fptr);
}

I can't seem to figure out why it only outputs the most recent data point and not all of it. any hints as to why it would do this?

Many thanks Steve

Upvotes: 0

Views: 160

Answers (1)

Dipjyoti_Biswas
Dipjyoti_Biswas

Reputation: 51

Write the line ptr = fopen("student.txt", "a+"); outside the loop. You will gel what you want.

struct students
{
    char *familyName[20], *firstName[20];
    int enrolNum, mark1, mark2, mark3;
} st[1000];

FILE *fptr;
int studentNum;
int i = 0;
void main()
{
    double markOne, markTwo, markThree;

    markOne = st[i].mark1 * 0.30;
    markTwo = st[i].mark2 * 0.40;
    markThree = st[i].mark3 * 0.30;
    char *fName;
    ptr = fopen("student.txt", "a+");
    do
    {

        fprintf(fptr, "Family name \tFirst name \tenrolment number \tartefact mark 1 \tartefact mark 2 \tartefact mark 3 \n");
        fprintf(fptr,"%s \t\t%s \t\t%d \t\t\t%.1f%% \t\t%.1f%%  \t\t%.1f%% \n", st[i].familyName, st[i].firstName, st[i].enrolNum, markOne, markTwo, markThree);
        printf("\n%d\n%d", i, studentNum);
    } while( i < studentNum);
    fclose(fptr);
}

The problem with your code is that ptr = fopen("student.txt", "a+"); is getting called every time the loop is executing. And the file ptr is opened again. It has not been closed during previous iteration. If you add fclose(fptr); in the loop, it will also work.

Upvotes: 2

Related Questions