Question

IN C ONLY As mentioned earlier there are two changes we are going to make from...

IN C ONLY

As mentioned earlier there are two changes we are going to make from lab 5,

The file you read into data structures can be any length.

studentInfo array will be stored in another struct called studentList that will contain the Student pointer and current length of the list.

Sometimes data can be used in structs that correlate between variables so it's convenient to store the data in the same struct. Instead of tracking a length variable all the way through our program, we will create a struct that stores the total number of current students in the list and the list itself. To do this, you can reuse some of the code YOU wrote in lab05 and implement the ability to read files of any size.

You will write the following functions (newStudent, freeStudent, and freeStudentArray will be the exact same),

Similar Functions from lab05

newStudent - Return a new student from a single string passed "student name, number"

freeStudent - Free any of the allocated memory from within the student struct.

freeStudentArray - Free all memory associated with any memory allocated in the array.

readStudentFile - Read an entire text file into a single studentList struct. The struct is a pointer and reallocates memory as needed (make sure you actually opened the file). You can reallocate memory for studentList->

Entirely new functions for lab06

addStudent - A "wrapper" function to add a student to the studentList->list. If there is not enough memory, you need to allocate more memory in increments of 5 students.

freeAllStudents - Free all memory inside a list of structs (including all memory in each struct).

Hint 1: Use fgets() to read from a file into a buffer before creating a student. Continue to read from the file until fgets returns null (while(fgets != null)).

Hint 2: Use strtok to split the string passed to newStudent.

Hint 3: atoi converts a string to integer.

Hint 4: Remember to allocate memory for your studentList before assigning pointers.

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

struct studentInfo

{

char *name;

int number;

};

typedef struct studentInfo Student;

struct studentList

{

int length;

Student *list;

};

typedef struct studentList List;

Student newStudent(char *string);

void freeStudent(Student student);

void freeStudentArray(Student *studentList, int length);

List *readStudentFile(char *fileName);

void addStudent(List *studentList, char *toAdd);

void freeAllStudents(List *studentList);

/************************************************************************************************************************************************/

int main(int argc, char *argv[]) {

List *all = NULL;

int i;  

  

if (argc < 1) {

printf("No file name was specified... Now exiting \n");

exit(0);

} else {

all = readStudentFile(argv[1]);

}

  

printf("Now printing the student list before freeing the allocated memory \n");

for (i = 0; i < all->length; i++) {

printf("\t%d: %s, %d\n", i, all->list[i].name, all->list[i].number);

}

  

/* Free memory */

freeAllStudents(all);

free(all);

  

return 0;

}

/**********************************************************************************************************/

/* Creating a new struct from a string in the form "name, studentNumber" */

Student newStudent(char *string)

{

Student new;

char *token = strtok(string, ",");

int i = 0;

while (token != NULL) /*Loops as long as Token is not empty*/

{

if (i % 2 == 0)

{

//allocate memory for name

new.name = (char*)malloc(strlen(token)+1 * sizeof(char));

strcpy(new.name, token);

}

else

{

new.number = atoi(token);

}

token = strtok(NULL, ",");

++i;

}

return new;

}

/* Free any memory allocated inside of the student struct */

void freeStudent(Student studentToFree)

{

free(studentToFree.name);

}

/* Free all associated memory of a list of structs (including all memory in each struct)*/

void freeStudentArray(Student *studentList, int length)

{

int i;

for(i = 0 ; i < length;i++)

{

freeStudent(studentList[i]);

}

}

/* Read an entire file and return a dynamically allocated array */

List *readStudentFile(char *fileName)

{

/*

This is the function from last lab that must me changed to meet these specifications

As mentioned earlier there are two changes we are going to make from lab 5,

The file you read into data structures can be any length.

studentInfo array will be stored in another struct called studentList that will contain the Student pointer and current length of the list.

*/

/* Initialize the student List pointer (allocate memory), allocate enough memory to store 5 students */

List *allStudents = NULL;

char buffer[50];

FILE *fPtr;

int studentCount = 0;

/* Allocate enough memory to store 5 students */

allStudents->list = (Student*)malloc(5 * sizeof(Student));

/* Open the file in read mode and see if it exists */

fPtr = fopen("testFile.txt", "r");

if (fPtr == NULL)

{

printf("Error opening input file\n");

return NULL;

}

while (fgets(buffer,50,fPtr) != NULL)

{

allStudents->list[studentCount++]=newStudent(buffer);

}

allStudents->length=studentCount--;

return allStudents;

}

/************* Functions to Be Completed ************************/

/* Allocate more memory for the list when the memory is full, then add to the back of the list */

void addStudent(List *studentList, char *toAdd)

{

/* Hint: use the length studentList->length */

}

/* Free all memory inside a list of structs (including all memory in each struct)*/

void freeAllStudents(List *studentList)

{

/* Hint: this function can be written easily in a couple lines (reuse other code) */

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

struct studentInfo

{

char *name;

int number;

};

typedef struct studentInfo Student;

struct studentList{

int length;

Student *list;

};

typedef struct studentList List;

Student newStudent(char *string);

void freeStudent(Student student);

void freeStudentArray(Student *studentList, int length);

List *readStudentFile(char *fileName);

void addStudent(List *studentList, char *toAdd);

void freeAllStudents(List *studentList);

/************************************************************************************************************************************************/

int main(int argc, char *argv[]){

List *all = NULL;

int i;

if (argc < 1){

printf("No file name was specified... Now exiting \n");

exit(0);

}

else{

all = readStudentFile(argv[1]);

}

printf("Now printing the student list before freeing the allocated memory \n");

for (i = 0; i < all->length; i++){

printf("\t%d: %s, %d\n", i, all->list[i].name, all->list[i].number);

}

/* Free memory */

freeAllStudents(all);

free(all);

return 0;

}

/**********************************************************************************************************/

/* Creating a new struct from a string in the form "name, studentNumber" */

Student newStudent(char *string){

Student new;

char *token = strtok(string, ",");

int i = 0;

while (token != NULL) /*Loops as long as Token is not empty*/

{

if (i % 2 == 0){

//allocate memory for name

new.name = (char *)malloc(strlen(token) + 1 * sizeof(char));

strcpy(new.name, token);

}

else{

new.number = atoi(token);

}

token = strtok(NULL, ",");

++i;

}

return new;

}

/* Free any memory allocated inside of the student struct */

void freeStudent(Student studentToFree){

free(studentToFree.name);

}

/* Free all associated memory of a list of structs (including all memory in each struct)*/

void freeStudentArray(Student *studentList, int length){

int i;

for (i = 0; i < length; i++){

freeStudent(studentList[i]);

}

}

/* Read an entire file and return a dynamically allocated array */

List *readStudentFile(char *fileName){

/*

This is the function from last lab that must me changed to meet these specifications

As mentioned earlier there are two changes we are going to make from lab 5,

The file you read into data structures can be any length.

studentInfo array will be stored in another struct called studentList that will contain the Student pointer and current length of the list.

Initialize the student List pointer (allocate memory), allocate enough memory to store 5 students */

List *allStudents = NULL;

char buffer[50];

FILE *fPtr;

int studentCount = 0;

/* Allocate enough memory to store 5 students */

allStudents = (List *)malloc(sizeof(List));

allStudents->list = (Student *)malloc(5 * sizeof(Student));

/* Open the file in read mode and see if it exists */

fPtr = fopen(fileName, "r");

if (fPtr == NULL){

printf("Error opening input file\n");

return NULL;

}

while (fgets(buffer, 50, fPtr) != NULL){

//allStudents->list[studentCount++] = newStudent(buffer);

addStudent(allStudents, buffer);

studentCount++;

}

allStudents->length = studentCount--;

return allStudents;

}

/************* Functions to Be Completed ************************/

/* Allocate more memory for the list when the memory is full, then add to the back of the list */

void addStudent(List *studentList, char *toAdd){

/* Hint: use the length studentList->length */

if(studentList->length>=5){

studentList->list = (Student *)realloc(studentList->list, (studentList->length+1)*sizeof(Student));

}

studentList->list[studentList->length] = newStudent(toAdd);

studentList->length++;

}

/* Free all memory inside a list of structs (including all memory in each struct)*/

void freeAllStudents(List *studentList){

/* Hint: this function can be written easily in a couple lines (reuse other code) */

freeStudentArray(studentList->list, studentList->length);

studentList->length=0;

}

Add a comment
Know the answer?
Add Answer to:
IN C ONLY As mentioned earlier there are two changes we are going to make from...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please explain how these code run for each line #include<stdio.h> #include<string.h> /** * Part A */...

    Please explain how these code run for each line #include<stdio.h> #include<string.h> /** * Part A */ struct myWord{    char Word[21];    int Length; }; int tokenizeLine(char line[], struct myWord wordList[]); void printList(struct myWord wordList[], int size); void sortList(struct myWord wordList[], int size); /** * main function */ int main() {    struct myWord wordList[20];    char line[100];    printf("Enter an English Sentence:\n");    gets(line);    int size = tokenizeLine(line, wordList);    printf("\n");    printf("Unsorted word list.\n");    printList(wordList, size);...

  • // READ BEFORE YOU START: // You are given a partially completed program that creates a...

    // READ BEFORE YOU START: // You are given a partially completed program that creates a list of students for a school. // Each student has the corresponding information: name, gender, class, standard, and roll_number. // To begin, you should trace through the given code and understand how it works. // Please read the instructions above each required function and follow the directions carefully. // If you modify any of the given code, the return types, or the parameters, you...

  • For the following task, I have written code in C and need help in determining the...

    For the following task, I have written code in C and need help in determining the cause(s) of a segmentation fault which occurs when run. **It prints the message on line 47 "printf("Reading the input file and writing data to output file simultaneously..."); then results in a segmentation fault (core dumped) I am using mobaXterm v11.0 (GNU nano 2.0.9) CSV (comma-separated values) is a popular file format to store tabular kind of data. Each record is in a separate line...

  • ASSIGNMENT DUE DATE GOT PUSHED BACK TO LATE THIS WEEK. PLEASE READ COMMENTS AND CODE BEFORE...

    ASSIGNMENT DUE DATE GOT PUSHED BACK TO LATE THIS WEEK. PLEASE READ COMMENTS AND CODE BEFORE ANSWERING CODING SECTIONS HW07 #Q1-Q5 HW08 #Q1-Q2 // READ BEFORE YOU START: // Please read the given Word document for the project description with an illustrartive diagram. // You are given a partially completed program that creates a list of students for a school. // Each student has the corresponding information: name, standard, and a linked list of absents. // Please read the instructions...

  • Finish the code below (using bubble sort) to sort the datafile in ascending order. each number...

    Finish the code below (using bubble sort) to sort the datafile in ascending order. each number should stop after "t" #include #include #include int main() { char letter[1400]; int length; FILE *fptr; if ((fptr = fopen("datafile1.txt","r")) == NULL) { printf("Error! opening file"); return (1); } if (fgets(letter,5000,fptr) != NULL) { printf("The string is in the file is\n\n"); puts(letter); } fclose(fptr); printf("\n\n"); length = strlen(letter); sortascending(length,letter); puts(letter); return 0; } ***datafile1.txt*** 1804289383t846930886t681692777t1714636915t1957747793tn424238335t719885386t1649760492t596516649t1189641421tn1025202362t1350490027t783368690t1102520059t2044897763tn1967513926t1365180540t1540383426t304089172t1303455736tn35005211t521595368t294702567t1726956429t336465782tn861021530t278722862t233665123t2145174067t468703135tn1101513929t1801979802t1315634022t635723058t1369133069tn1125898167t1059961393t2089018456t628175011t1656478042tn1131176229t1653377373t859484421t1914544919t608413784tn756898537t1734575198t1973594324t149798315t2038664370tn1129566413t184803526t412776091t1424268980t1911759956tn749241873t137806862t42999170t982906996t135497281tn511702305t2084420925t1937477084t1827336327t572660336tn1159126505t805750846t1632621729t1100661313t1433925857tn1141616124t84353895t939819582t2001100545t1998898814tn1548233367t610515434t1585990364t1374344043t760313750tn1477171087t356426808t945117276t1889947178t1780695788tn709393584t491705403t1918502651t752392754t1474612399tn2053999932t1264095060t1411549676t1843993368t943947739tn1984210012t855636226t1749698586t1469348094t1956297539tn update** I'm supposed to write a code that scans...

  • I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any...

    I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any help would be appreciated. /**** main.c ****/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <string.h> #define WORD_LEN 6 #define TOP 10 char * delim = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r"; struct Word { char word[30]; int freq; }; int threadCount; int fileDescriptor; int fileSize; off_t chunk; struct Word* wordArray; int arrIndex = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;...

  • Need this in C The starter code is long, if you know how to do it...

    Need this in C The starter code is long, if you know how to do it in other way please do. Do the best you can please. Here's the starter code: // ----------------------------------------------------------------------- // monsterdb.c // ----------------------------------------------------------------------- #include #include #include // ----------------------------------------------------------------------- // Some defines #define NAME_MAX 64 #define BUFFER_MAX 256 // ----------------------------------------------------------------------- // Structs typedef struct { char name[NAME_MAX]; int hp; int attackPower; int armor; } Character; typedef struct { int size; Character *list; } CharacterContainer; // ----------------------------------------------------------------------- //...

  • C programming The program will require the following structure: struct _data { char *name; long number;...

    C programming The program will require the following structure: struct _data { char *name; long number; }; The program will require command line arguments: int main(int argv, char **argc) { Where argv is the number of arguments and argc is an array holding the arguments (each is a string). Your program must catch any case where no command line arguement was provided and print a warning message (see below). You MUST include/use the following functions, defined as follows: int SCAN(FILE...

  • Let’s build a dynamic string tokenizer! Start with the existing template and work on the areas...

    Let’s build a dynamic string tokenizer! Start with the existing template and work on the areas marked with TODO in the comments: Homework 8 Template.c Note: If you turn the template back into me without adding any original work you will receive a 0. By itself the template does nothing. You need to fill in the code to dynamically allocate an array of strings that are returned to the user. Remember: A string is an array. A tokenizer goes through...

  • // Write the compiler used: Visual studio // READ BEFORE YOU START: // You are given...

    // Write the compiler used: Visual studio // READ BEFORE YOU START: // You are given a partially completed program that creates a list of patients, like patients' record. // Each record has this information: patient's name, doctor's name, critical level of patient, room number. // The struct 'patientRecord' holds information of one patient. Critical level is enum type. // An array of structs called 'list' is made to hold the list of patients. // To begin, you should trace...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT