brehon1104
brehon1104

Reputation: 63

fscanf, structs, and using the struct c programming

/*Project 1
Student records

1. Read the file with the records
2. store them
3. sort them
4. output them

ex. input and output (SORTED by student ID

2040003 AAAA BBBBBBBBB ComputerScience 3.45
2040002 AAA CCC ElectricalEngineering 3.01
2040005 AAAAAAAAAAAAAAAAA BBB ComputerScience 3.60

2040002,AAA,CCC,ElectricalEngineering,3.01
2040003,AAAA,BBBBBBBBB,ComputerScience,3.45
2040005,AAAAAAAAAAAAAAAAA,BBB,ComputerScience,3.60

char* name = malloc(256*sizeof(char));
*/ 

int main()
{
typedef struct StudentRecords
{
    int StudentID; //must be of size 7 between 1000000 and 9999999
    char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
    char *Lastname; //= MALLOC(256*sizeof(char));
    char *Department; //= MALLOC(256*sizeof(char));
    float GPA; // must be between 0 and 4
} STUDENTRECORDS; 

/*
    First job is read the file
*/

//set variables
int i=0;
char filecontent, file_name[100];
FILE *fp;
STUDENTRECORDS StudentRecords[300];
STUDENTRECORDS a[300];
int size =0;


printf("Enter directory of file\n"); // instructs user to enter directory of file
gets(file_name); //prompt use

fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()

// here is a check to see if fp is empty and throw an error if so
if (fp == NULL)
{
        perror("Could not open file\n");
        exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name); // just prints the file name (file_name) you are prompted for

// here is where the printing of contents actually occurs
while ((filecontent = fgetc(fp)) != EOF) // I think EOF is end of feed here, not 100%
{
    printf("%c",filecontent);
}

//I thought this line was to figure out how many lines are in the text, but it isnt working.
while (!feof(fp)) 
{
        read(StudentRecords, i, fp);
        i++;
}

//because the while statement isnt working, Ive elected to setting size to 3 in order to continue coding.
size = i = 3;
printf("Size = %d\n", size);

//I thought this essentially put the files contents into 
for (i = 0; i < size; ++i)
    fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);

for (i = 0; i < size; ++i)
    printf("%s", StudentRecords[i]);
    //printf("%d %s %s %s %f/n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);

for (i = 0; i < size; ++i)
    fscanf(fp, "%d %s %s %s %f\n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);

for (i = 0; i < size; ++i)
    printf("%s", a[i]);
    //printf("%d %s %s %s %f/n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);


// fclose() must follow an fopen()
fclose(fp);

//printf("%g", &StudentRecords);


// return code
return 0;

}

How do I add information into a struct and print it or use it? This is what i have so far. I've tried many different things and to no avail. I think the problem is with my initializing my struct for use. I can't get it right. I've tried searching for a solution, but each one is different and don't explain much.

Thanks for any suggestions.

Upvotes: 0

Views: 3184

Answers (2)

James McPherson
James McPherson

Reputation: 2566

A few comments, and some suggestions:

Was it your lecturer who said to use a linked-list? If so.. you really should do that otherwise you'll lose marks for failing to meet the spec.

EOF is 'End Of File'. feof() tells you if the stream pointer passed to it has hit EOF already.

Your while loop to print the contents is inefficient. Rather than reading every. single. character. in. the. file., you should read the entire file (or at least, large chunks thereof, let's not assume infinite memory), fclose() the stream and then operate on the read-in file.

Also, this sort of exercise lends itself very well to fixed-size record

Omitting error handling, variable declarations, structures and using some pseudocode:

stat("/path/to/file", &statbuf)
inputfd = fopen("/path/to/file", r);
/* assuming that we only have a small file... */
contents = calloc(statbuf.st_size * sizeof(char));
/* read it all in, in one big chunk */
fread(contents, statbuf.st_size, 1, inputfd);
fclose(inputfd);

/* Now you can operate on it however you like */
bytesleft = statbuf.st_size;
/*
 * this might need to go at the top of your block, depends on if you
 * have enabled C99
 */
char eachline[MAXLINELENGTH];
int n = 0;
while (bytesleft > 0) {
    add_new_list_element(mylist);
    bzero(eachline, MAXLINELENTH);
    memccpy(&eachline, contents[n], '\n', MAXLINELENGTH);
    bytesleft -= sizeof(eachline);
    nread = sscanf(start, "USE YOUR FORMAT STRING HERE", [variable list]);
    if (nread < 0)
        /* handle EOF, remember to make use of errno */
}

call_my_sort_function(mylist);
for (; thiselement != NULL; thiselement = thiselement->next)
    print_salient_field_values(thiselement);

Upvotes: 0

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25875

Please find example code for reading content from file and storing it in structure also for this example have only take 5 student data entry(you can change as you wish) And on which criteria you want to do sorting? So i leave sorting on you.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_ENTRY 5
typedef struct StudentRecords
{
    int StudentID; //must be of size 7 between 1000000 and 9999999
    char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
    char *Lastname; //= MALLOC(256*sizeof(char));
    char *Department; //= MALLOC(256*sizeof(char));
    float GPA; // must be between 0 and 4
} STUDENTRECORDS; 

int main()
{
    /*
        First job is read the file
    */

    //set variables
    int i=0;
    char filecontent, file_name[100];
    FILE *fp;

    STUDENTRECORDS StudentRecords[MAX_ENTRY];

    for(i=0;i<MAX_ENTRY;i++)
    {
        StudentRecords[i].Firstname = malloc(sizeof(char)*256);
        StudentRecords[i].Lastname = malloc(sizeof(char)*256);
        StudentRecords[i].Department = malloc(sizeof(char)*256);        
    }

    printf("Enter directory of file\n"); // instructs user to enter directory of file
    gets(file_name); //prompt use

    fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()

    // here is a check to see if fp is empty and throw an error if so
    if (fp == NULL)
    {
        perror("Could not open file\n");
        //exit(EXIT_FAILURE);
    }

    i=0;
    while(EOF!=fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, &StudentRecords[i].GPA))
    {
        printf("%d %s %s %s %f\n", StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, StudentRecords[i].GPA);
        i++;
    }


    // fclose() must follow an fopen()
    fclose(fp);

    return 0;
}

Note: never forgot to free string which allocated by malloc after it's use.

Upvotes: 2

Related Questions