C program, hard q please help?

Not sure how to continue on.

c program, help required? 

Could anybody show me the first few lines required for the function main please? 

#include <stdio.h> 

#include <stdlib.h> 

int main(void){ 

FILE * infile; 

long id, 

char name[20]; 

int a1,a2,a3; 



printf("Sorry! Cannot open this file\n"); 

return -1; 

fscanf(infile,"%d %s %d %d %d ",&id, name,&a1,&a2,&a3);

The file indata.txt 

113344 John 2 300 3000 

115544 Liam 2 200 3000 

112244 Paul 1 50 3000 

123388 Jack 1 100 3000 

125544 Lisa 3 200 3000 

126699 Aoife 2 100 3000 

117700 Gina 2 100 3000 

113444 Paula 3 100 3000 

114377 Tom 4 200 3000

Attachment image

1 Answer

  • 5 years ago
    Best Answer

    I can show you a few lines BEFORE the start of main, which is more important for this assignment. You are supposed to be storing data in an array of structs, which means you need to define a struct type.

    typedef struct student_t


    long id;

    char name[31];

    int nosiblings;

    int distance_from_school;

    int fee;

    int reduced_fee;

    } student_t;

    Your start is not only missing the struct type, it ignores the instruction that names can be up to 30 characters long, meaning you need at least 31 positions in the char[] array for the name to allow for the terminating 0 byte.

    If you instructor is teaching you to use %s with fscanf (or any of the other scanf functions), you are being taught an old, unsafe format. You should ALWAYS specify a maximum length with %s input formats. Change %s to %30s in the format string so that fscanf will not read more than 30 characters for the name.

    The instructions ask you to create an array, but don't say how many records to expect. Pick a number, I guess, but you should get this point cleared up before you get too far into coding. How many records do you need to support? If there is no upper limit, you need to use dynamic allocation with calloc() or malloc(), and be prepared to reallocate when the array fills up.

    To allow for 500 records, you could add:

    #define MAX_STUDENTS 500

    ...near the top of the program. Symbolic constants usually appear after the #includes but before other definitions, but anywhere before the first use works with #define. Then, in main, you can define:

    student_t students[MAX_STUDENTS];

    int count = 0; /* count of entries used in students[] array. */

    To read an entry and add it to the end of the array:

    n = fscanf("%ld %30s %d %d %d", &students[count].id, students[count].name,

    &students[count].nosiblings, &students[count].distancefromschool, &students[count].fee);

    if (n==5) /* if fscanf() successfully read all 5 fields */


    students[count].reducedfee = 0; /* replace this with a calculation of the correct reduced fee */

    ++count; /* update record count */


    else { .... complain and halt on bad input .... }

Still have questions? Get your answers by asking now.