0

I want to ask about file processing and struct in C language. I am given an assignment where I need to have a .txt file containing: the names of basketball teams, the games they have played in total, the amount of games they have won, etc.. Here is the task:

  1. Get data from user-specified .txt file (eg "data.txt")
  2. Store the data in array of struct
  3. Let the user have the ability to sort by name or the total amount of wins they have.

Here is an example, "data.txt" file:

Structure : name, games played, won at home, lost at home, won away, lost away

Fenerbahce-Dogus 25 12 0 10 3
Tofas 25 11 2 9 3
Anadolu-Efe 26 13 1 6 6
Banvit 26 9 4 8 5
Darussafaka 26 11 2 4 9

So far, I have been trying to allocate a dynamic array (of struct) and save the data from the txt file into said array. However, the program stops responding immediately whenever I try to enter the said "data.txt". as input. Could anybody inform me why this is happening and what should I do to get past this error?

Here is the code:

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

typedef struct {
        char *name;
        int games;
        int winsHome, losesHome;
        int winsAway, losesAway;
        int winsTotal, losesTotal;
        int totalPoints;
} scoreboard;


void Load_Scoreboard_Table(char *, scoreboard *);

int main(){
    char fileName[40];
    FILE *inputFile;
    while (1){
        printf("Enter the file name> ");
        gets(fileName);
        inputFile = fopen(fileName,"r");
        if (inputFile != NULL){
            break;
        }
        printf("ERROR: The file %s could not be opened.\n",fileName);
        printf("Please verify that the file exists.\n");
    }
    int listLength=0;
    char curChar;
    while ((curChar=fgetc(inputFile))!=EOF){
        if (curChar=='\n'){
            listLength++;
        }
    }
    fclose(inputFile);
    scoreboard *scoreboard_table = (scoreboard *)malloc(sizeof(scoreboard) * listLength);
    Load_Scoreboard_Table(fileName,scoreboard_table);
    return 0;
}

void Load_Scoreboard_Table(char *fileName,scoreboard *scoreboard_table){
    FILE *inputFile;
    fopen(fileName,"r");
    int i=0;
    while (fscanf(inputFile, "%s %d %d %d %d %d\n", (scoreboard_table+i)->name,(scoreboard_table+i)->games,(scoreboard_table+i)->winsHome,(scoreboard_table+i)->losesHome,(scoreboard_table+i)->winsAway,(scoreboard_table+i)->losesAway)!=EOF){
        (scoreboard_table+i)->winsTotal = (scoreboard_table+i)->winsHome + (scoreboard_table+i)->winsAway;
        (scoreboard_table+i)->losesTotal = (scoreboard_table+i)->losesHome + (scoreboard_table+i)->losesAway;
        (scoreboard_table+i)->totalPoints = (((scoreboard_table+i)->winsTotal)*2) + (scoreboard_table+i)->losesTotal;
        i++;
    }
}

Update:

I have managed to read from the file and save it in struct array.(Also added a print function). However I still cannot get it to stop freezing once it finishes printing the function (it would freeze after saving data into the array before). Note: I know many people have warned me not to use gets; but, my teacher told me to use it for now. Note2: I decided to have a static char name inside the struct Note3: I have only learned about data structures today, so I'm VERY new to the topic; therefore, please explain things without going into too much detail. What could be causing the code below to freeze?

Code:

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

typedef struct {                 // defining a struct here
    char name[40];               // name of the sports club
    //clubs containing multiple words should be written in the following format: 'name-name-name'
    //ex : 'Anadolu Efe' should be written as 'Anadolu-Efe' in the text file
    //This is to avoid confusion when reading from .txt file
    int games;
    int winsHome, losesHome;
    int winsAway, losesAway;
    int winsTotal, losesTotal;
    int totalPoints;
} scoreboard;

void Load_Scoreboard_Table(char *, scoreboard *); // reads the .txt file and saves the contents into scoreboard_table
void Display_Scoreboard_Table(scoreboard *, int); // displays scoreboard_table, also takes it's size as input

int main(void){
    char fileName[40]; // the name of the file will be stored here (ex: data.txt)
    FILE *inputFile;   // creating a stream to read from .txt file
    while (1){         // Ask user for the name of the file until said file is opened for reading
            printf("Enter the file name> ");
            gets(fileName); // get string input from user that supports space characters (eg: "data.txt")
            inputFile = fopen(fileName,"r"); // try opening file in read mode
            if (inputFile != NULL){ //if the file has succesfully opened, then break from the loop
                    break;
            }
            printf("ERROR: The file %s could not be opened.\n",fileName); //if the file was not succesfully opened, then print appropriate error message
            printf("Please verify that the file exists.\n");
    }
    int listLength=0; //will be used to dynamically allocate memory for scoreboard_table array (array of structs)
    int curChar;   // I figured that fgetc returns an integer value
    while ((curChar=fgetc(inputFile))!=EOF){  //get a character until EOF
            if (curChar=='\n'){               //if it's a newline character then we need to allocate more memory for scoreboard_table array
                    listLength++;
            }
    }
    fclose(inputFile); // close the file as it's job is done
    scoreboard *scoreboard_table = malloc(sizeof(scoreboard) * listLength); // allocating enough memory to store the contents of .txt file
    Load_Scoreboard_Table(fileName,scoreboard_table); //save the contents of file on scoreboard_table 
    while (1){
        Display_Scoreboard_Table(scoreboard_table,listLength);
        break;
    }
    free(scoreboard_table); //freeing memory allocated for scoreboard_table
    return 0;
}

void Load_Scoreboard_Table(char *fileName,scoreboard *scoreboard_table){
    FILE *inputFile = fopen(fileName,"r"); // creating stream to read from file
    if(inputFile == NULL ) {               //checking again just in case there is a problem opening the file
        printf("ERROR: The file %s could not be opened.\n",fileName);
        exit(1);
    }
    int i=0,j,k;
    //the loop below gets data from .txt file line by line until EOF and stores it in scoreboard_table array
    while (fscanf(inputFile,"%s %d %d %d %d %d", (scoreboard_table+i)->name,&(scoreboard_table+i)->games,&(scoreboard_table+i)->winsHome,&(scoreboard_table+i)->losesHome,&(scoreboard_table+i)->winsAway,&(scoreboard_table+i)->losesAway) != EOF){
            (scoreboard_table+i)->winsTotal = (scoreboard_table+i)->winsHome + (scoreboard_table+i)->winsAway;
            (scoreboard_table+i)->losesTotal = (scoreboard_table+i)->losesHome + (scoreboard_table+i)->losesAway;
            (scoreboard_table+i)->totalPoints = (((scoreboard_table+i)->winsTotal)*2) + (scoreboard_table+i)->losesTotal;
            i++;
    }
    //the loop below replaces the '-' characters with ' ' in the name of every scoreboard_table array
    for (j=0;j<i;j++){
        for (k=0;k<40;k++){
            if ((scoreboard_table+i)->name[k] == '-'){
                (scoreboard_table+i)->name[k] = ' ';
            }
        }
    }
    printf("Score records file has been successfully loaded!\n");
}

void Display_Scoreboard_Table(scoreboard *scoreboard_table,int size){
    printf("Team                                        G     WH     LH     WA     LA     Won     Lost     Points\n");
    int i;
    for (i=0;i<=size;i++){
        printf("%-40s%5d  %5d  %5d  %5d  %5d   %5d    %5d      %5d\n",(scoreboard_table+i)->name,(scoreboard_table+i)->games,(scoreboard_table+i)->winsHome,(scoreboard_table+i)->losesHome,(scoreboard_table+i)->winsAway,(scoreboard_table+i)->losesAway,(scoreboard_table+i)->winsTotal,(scoreboard_table+i)->losesTotal,(scoreboard_table+i)->totalPoints);
    }
}

Thank you.

Update 2 (With working code):

The issue was caused by me allocating wrong amount of memory for the array of structs called scoreboard_table. To be more specific, I was allocating memory for array that could hold 1 less line than the file. I have updated the code again. It is working now... (For the most part, except when an unexpected input is entered(such as being fed an empty file, or user entering more characters into gets).) This code is more than enough for my assignment as my teachers have not asked for a more detailed program(infact, they do get angry if we submit more complicated programs since we have not yet learnt about them in class - which is why I'm using gets() and not fgets() for example). However I'm curious to hear your opinions on the matter. What do you think I should do to improve this? By the way, I am aware of the grammar-spelling mistakes in the code. It's just because we need to strictly obey the input-output format in our assignments and typing things differently means losing points. Code:

/* -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
                                          ~ ~ ~ ~ VERY IMPORTANT ~ ~ ~ ~
        The text file containing the data should be written in the following format:
        "%s %d %d %d %d %d\n" where
        %s is the name of the club
        If the name of the club contains more than one word, it should be written without any space characters ' '; instead place dash characters '-'
        Example: 'Anadolu Efe' should be written as 'Anadolu-Efe' in the text file
        complete line example:
        "Anadolu-Efe 26 13 1 6 6"

   -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-        */

//including required libraries
#include <stdio.h>  
#include <stdlib.h> //used to dynamically allocate memory
#include <string.h> //used for some string manipulation functions

typedef struct {                 // defining a struct here
    char name[40];               // name of the sports club
    //clubs containing multiple words should be written in the following format: 'name-name-name'
    //ex : 'Anadolu Efe' should be written as 'Anadolu-Efe' in the text file
    //This is to avoid confusion when reading from .txt file
    int games;
    int winsHome, losesHome;
    int winsAway, losesAway;
    int winsTotal, losesTotal;
    int totalPoints;
} scoreboard;

void Load_Scoreboard_Table(char *, scoreboard *); // reads the .txt file and saves the contents into scoreboard_table
void Display_Scoreboard_Table(scoreboard *, int); // displays scoreboard_table, also takes it's size as input
void Search(scoreboard *, int, char *);           // searches if a team exists in the scoreboard array and if there is; it prints the stats of the team
void interactive_board(scoreboard *, int, int);   // sorts the scoreboard array depending on user input, (sort by: games, points)

/*
This program reads data from a txt data, stores it in an array of structs
The program has the ability to sort the array based on either points or games
It also can search for the name inside said array of structs
*/

int main(){
    char fileName[40];   // the name of the file will be stored here (ex: data.txt)
    char searchTerm[40]; // search term will be stored here
    FILE *inputFile;     // creating a stream to read from .txt file
    int i;               // will be used later in a loop
    while (1){           // Ask user for the name of the file until said file is opened for reading
            printf("Enter the file name: ");
            gets(fileName); // get string input from user that supports space characters (eg: "data.txt")
            inputFile = fopen(fileName,"r"); // try opening file in read mode
            if (inputFile != NULL){ //if the file has succesfully opened, then break from the loop
                    break;
            }
            printf("ERROR: The file %s could not be opened.\n",fileName); //if the file was not succesfully opened, then print appropriate error message
            printf("Please verify that the file exists.\n");
    }
    int listLength=1; //will be used to dynamically allocate memory for scoreboard_table array (array of structs)
    int curChar;   // I figured that fgetc returns an integer value
    while ((curChar=fgetc(inputFile))!=EOF){  //get a character until EOF
            if (curChar=='\n'){               //if it's a newline character then we need to allocate more memory for scoreboard_table array
                    listLength++;
            }
    }
    fclose(inputFile); // close the file as it's job is done
    scoreboard *scoreboard_table = malloc(sizeof(scoreboard) * (listLength)); // allocating enough memory to store the contents of .txt file
    if (scoreboard_table == NULL){
        printf("ERROR: There has been an error allocating memory for scoreboard table array.\n");
        exit(1);
    }
    Load_Scoreboard_Table(fileName,scoreboard_table); //save the contents of file on scoreboard_table 
    Display_Scoreboard_Table(scoreboard_table,listLength);
    while (1){
        printf("Enter the name of the team (Exit - X, Sort -S): ");
        gets(searchTerm);
        i=0;
        while (searchTerm[i]!='\0'){
            searchTerm[i]=toupper(searchTerm[i]);
            i++;
        }
        if (strcmp(searchTerm,"X")==0){
            printf("Bye!\n");
            free(scoreboard_table); //freeing memory allocated for scoreboard_table
            return 0;
        }
        else if (strcmp(searchTerm,"S")==0){
            printf("Sort by (G: games, P: points): ");
            gets(searchTerm);
            i=0;
            while (searchTerm[i]!='\0'){
                searchTerm[i]=toupper(searchTerm[i]);
                i++;
            }
            if (strcmp(searchTerm,"G")==0){
                interactive_board(scoreboard_table,listLength,1);
                Display_Scoreboard_Table(scoreboard_table,listLength);
            }
            else if (strcmp(searchTerm,"P")==0){
                interactive_board(scoreboard_table,listLength,2);
                Display_Scoreboard_Table(scoreboard_table,listLength);
            }
            else{
                printf("ERROR: Invalid input. There is no sort term for '%s'\n",searchTerm);
            }
        }
        else{
            Search(scoreboard_table,listLength,searchTerm);
        }
    }
}

void Load_Scoreboard_Table(char *fileName,scoreboard *scoreboard_table){
    FILE *inputFile = fopen(fileName,"r"); // creating stream to read from file
    if(inputFile == NULL ) {               //checking again just in case there is a problem opening the file
        printf("ERROR: The file %s could not be opened.\n",fileName);
        exit(1);
    }
    int i=0,j,k;
    //the loop below gets data from .txt file line by line until EOF and stores it in scoreboard_table array
    while (fscanf(inputFile,"%s %d %d %d %d %d", (scoreboard_table+i)->name,&(scoreboard_table+i)->games,&(scoreboard_table+i)->winsHome,&(scoreboard_table+i)->losesHome,&(scoreboard_table+i)->winsAway,&(scoreboard_table+i)->losesAway) != EOF){
            (scoreboard_table+i)->winsTotal = (scoreboard_table+i)->winsHome + (scoreboard_table+i)->winsAway;
            (scoreboard_table+i)->losesTotal = (scoreboard_table+i)->losesHome + (scoreboard_table+i)->losesAway;
            (scoreboard_table+i)->totalPoints = (((scoreboard_table+i)->winsTotal)*2) + (scoreboard_table+i)->losesTotal;
            i++;
    }
    //the loop below replaces the '-' characters with ' ' in the name of every scoreboard_table array
    for (j=0;j<i;j++){
        for (k=0;k<40;k++){
            if (*(((*(scoreboard_table+j)).name)+k) == '-' ){  //if the value of name[k] inside scoreboard_table[j] is equal to '-' character
                *(((*(scoreboard_table+j)).name)+k) = ' ';     //replace the value of scoreboard_table[j].name[k] to ' ' character
            }
        }
    }
    fclose(inputFile); // close the file as it's job is done
    printf("Score records file has been successfully loaded!\n"); // notify the user that reading from the file has been successful
}

void Display_Scoreboard_Table(scoreboard *scoreboard_table,int size){
    printf("\nTeam                                        G     WH     LH     WA     LA     Won     Lost     Points\n\n"); // the variables to be shown in table
    int i;
    for (i=0;i<size;i++){//for every element in scoreboard_table, print the variables stored
        printf("%-40s%5d  %5d  %5d  %5d  %5d   %5d    %5d      %5d\n",(scoreboard_table+i)->name,(scoreboard_table+i)->games,(scoreboard_table+i)->winsHome,(scoreboard_table+i)->losesHome,(scoreboard_table+i)->winsAway,(scoreboard_table+i)->losesAway,(scoreboard_table+i)->winsTotal,(scoreboard_table+i)->losesTotal,(scoreboard_table+i)->totalPoints);
    }
}

void Search(scoreboard *scoreboard_table, int size, char *searchTerm){ //search for name of team in scoreboard_table
    int i,j; //i = index of scoreboard_table array, j = index of name array inside scoreboard_table array
    char table_name[40]; //  will be used to convert scoreboard_table->name to uppercase and store it
    for (i=0;i<size;i++){  // for every element in scoreboard_table
        for (j=0;j<40;j++){  // for every character in the name of scoreboard_table[i]->name
            table_name[j]=toupper(*(((*(scoreboard_table+i)).name)+j)); //store the upper-case letter of scoreboard_table[i]->name[j] in table_name[j]
        }
        if (strcmp(table_name,searchTerm)==0){ 
        //if the search term is equal to table_name (which is uppercase version of scoreboard_table[i]->name), then print the statistics and break from the loop.
            printf("%s has %d win, %d lost and a total of %d points!\n",(scoreboard_table+i)->name,(scoreboard_table+i)->winsTotal,(scoreboard_table+i)->losesTotal,(scoreboard_table+i)->totalPoints);
            break;
        }
        else if(i==(size-1)){ 
        //   if it's the last element of scoreboard_table array and the search term is not equal to scoreboard_table[i]->name
        //   notify the user that their search term is not found in the scoreboard_table array
            printf("That team is unknown! Please try again!\n");
        }
    }
}

void interactive_board(scoreboard *scoreboard_table, int size, int sort){
    //this function sorts the scoreboard_table array using selection sort algorithm
    /*
    selection sort algorithm sorts an array by repeatedly finding the maximum element from unsorted part and putting it at the beginning.
    */
    int i,j,index;
    /*
    i is used in a for loop to get ith element of scoreboard_table
    j is used to determine when the sorting is complete
    (ie: if you have a list containing 5 elements, you need to sort the array 4 times at most(in this case, which is selection sort algorithm); 
    therefore j is used in a for loop : for (j=0;j<(sizeofArray-1);j++)
    j is also used to write into jth element of scoreboard_table
    */
    int max; //store the max value here
    scoreboard temp; //declare a struct named temp, will store temporary data when swapping variables of scoreboard_table array
    if (sort==1){ // if sorting based on games
        for (j=0;j<size-1;j++){ // explained above, iterate the code below (array) size-1 times
            max=(scoreboard_table+size-1)->games; //set max to the last element of the array since this is the unsorted part of array...
            index=size-1;                         //set index to index of last element of the array...
            for (i=j;i<size;i++){                 //no need to search elements with index less than j since they are already sorted
                                                  //therefore start searching elements from j till the last element
                if (max<((scoreboard_table+i)->games)){ 
                //if the value of current element > max, then the max value becomes this value and the index of the new max value is stored in index
                    max=(scoreboard_table+i)->games;
                    index=i;
                }
                if (i==(size-1)){ // swap the variables of scoreboard_table[index] with the variables of scoreboard_table[j]
                    //where j stands for the next unsorted member and index stands for the index of the largest variable
                    //copy contents of scoreboard_table[j] into temp (BACKUP)
                    strcpy(temp.name,(scoreboard_table+j)->name);
                    temp.games=(scoreboard_table+j)->games;
                    temp.losesAway=(scoreboard_table+j)->losesAway;
                    temp.losesHome=(scoreboard_table+j)->losesHome;
                    temp.losesTotal=(scoreboard_table+j)->losesTotal;
                    temp.totalPoints=(scoreboard_table+j)->totalPoints;
                    temp.winsAway=(scoreboard_table+j)->winsAway;
                    temp.winsHome=(scoreboard_table+j)->winsHome;
                    temp.winsTotal=(scoreboard_table+j)->winsTotal;
                    //copy contents of scoreboard_table[index] into scoreboard_table[j]
                    strcpy((scoreboard_table+j)->name,(scoreboard_table+index)->name);
                    (scoreboard_table+j)->games=(scoreboard_table+index)->games;
                    (scoreboard_table+j)->losesAway=(scoreboard_table+index)->losesAway;
                    (scoreboard_table+j)->losesHome=(scoreboard_table+index)->losesHome;
                    (scoreboard_table+j)->losesTotal=(scoreboard_table+index)->losesTotal;
                    (scoreboard_table+j)->totalPoints=(scoreboard_table+index)->totalPoints;
                    (scoreboard_table+j)->winsAway=(scoreboard_table+index)->winsAway;
                    (scoreboard_table+j)->winsHome=(scoreboard_table+index)->winsHome;
                    (scoreboard_table+j)->winsTotal=(scoreboard_table+index)->winsTotal;
                    //copy contents of temp (BACKUP) into scoreboard_table[index]
                    strcpy((scoreboard_table+index)->name,temp.name);
                    (scoreboard_table+index)->games=temp.games;
                    (scoreboard_table+index)->losesAway=temp.losesAway;
                    (scoreboard_table+index)->losesHome=temp.losesHome;
                    (scoreboard_table+index)->losesTotal=temp.losesTotal;
                    (scoreboard_table+index)->totalPoints=temp.totalPoints;
                    (scoreboard_table+index)->winsAway=temp.winsAway;
                    (scoreboard_table+index)->winsHome=temp.winsHome;
                    (scoreboard_table+index)->winsTotal=temp.winsTotal;
                }
            }
        }
    }
    else{ // if sorting based on points
        for (j=0;j<size-1;j++){ // explained above, iterate the code below (array) size-1 times
            max=(scoreboard_table+size-1)->totalPoints; //set max to the last element of the array since this is the unsorted part of array...
            index=size-1;                         //set index to index of last element of the array...
            for (i=j;i<size;i++){                 //no need to search elements with index less than j since they are already sorted
                                                  //therefore start searching elements from j till the last element
                if (max<((scoreboard_table+i)->totalPoints)){ 
                //if the value of current element > max, then the max value becomes this value and the index of the new max value is stored in index
                    max=(scoreboard_table+i)->totalPoints;
                    index=i;
                }
                if (i==(size-1)){ // swap the variables of scoreboard_table[index] with the variables of scoreboard_table[j]
                    //where j stands for the next unsorted member and index stands for the index of the largest variable
                    //copy contents of scoreboard_table[j] into temp (BACKUP)
                    strcpy(temp.name,(scoreboard_table+j)->name);
                    temp.games=(scoreboard_table+j)->games;
                    temp.losesAway=(scoreboard_table+j)->losesAway;
                    temp.losesHome=(scoreboard_table+j)->losesHome;
                    temp.losesTotal=(scoreboard_table+j)->losesTotal;
                    temp.totalPoints=(scoreboard_table+j)->totalPoints;
                    temp.winsAway=(scoreboard_table+j)->winsAway;
                    temp.winsHome=(scoreboard_table+j)->winsHome;
                    temp.winsTotal=(scoreboard_table+j)->winsTotal;
                    //copy contents of scoreboard_table[index] into scoreboard_table[j]
                    strcpy((scoreboard_table+j)->name,(scoreboard_table+index)->name);
                    (scoreboard_table+j)->games=(scoreboard_table+index)->games;
                    (scoreboard_table+j)->losesAway=(scoreboard_table+index)->losesAway;
                    (scoreboard_table+j)->losesHome=(scoreboard_table+index)->losesHome;
                    (scoreboard_table+j)->losesTotal=(scoreboard_table+index)->losesTotal;
                    (scoreboard_table+j)->totalPoints=(scoreboard_table+index)->totalPoints;
                    (scoreboard_table+j)->winsAway=(scoreboard_table+index)->winsAway;
                    (scoreboard_table+j)->winsHome=(scoreboard_table+index)->winsHome;
                    (scoreboard_table+j)->winsTotal=(scoreboard_table+index)->winsTotal;
                    //copy contents of temp (BACKUP) into scoreboard_table[index]
                    strcpy((scoreboard_table+index)->name,temp.name);
                    (scoreboard_table+index)->games=temp.games;
                    (scoreboard_table+index)->losesAway=temp.losesAway;
                    (scoreboard_table+index)->losesHome=temp.losesHome;
                    (scoreboard_table+index)->losesTotal=temp.losesTotal;
                    (scoreboard_table+index)->totalPoints=temp.totalPoints;
                    (scoreboard_table+index)->winsAway=temp.winsAway;
                    (scoreboard_table+index)->winsHome=temp.winsHome;
                    (scoreboard_table+index)->winsTotal=temp.winsTotal;
                }
            }
        }
    }
}
PlagueTR
  • 78
  • 2
  • 10
  • As I'm lazy right now (and hey, "lazy" is what drives good engineering .. hehe) -- how about you use a debugger, so you can tell us where exactly to look? :) –  May 08 '18 at 18:38
  • 1
    `gets` is bad. Don't use it. https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – Christian Gibbons May 08 '18 at 18:38
  • oh yes. as well as a plain `%s` in some `*scanf()` -> overflows any buffer. **Ban** `gets()` (it's removed from C for good reasons) entirely in favor of `fgets()` and with `scanf()`, use *field widths* –  May 08 '18 at 18:40
  • Writing these comments, I see you have `char *name` in your struct, never assign this to some meaningful pointer and still feed it to `scanf("%s", ...` -- sure this will crash, `scanf()` will try to write to some *indeterminate* location. –  May 08 '18 at 18:41

2 Answers2

0

Pay special attention to contents of your fscanf(). Addresses of int variables have to be passed it's the one of crashing reason of the code.

 while (fscanf(inputFile, "%s %d %d %d %d %d\n", 
 (scoreboard_table+i)->name, &(scoreboard_table+i)->games,
 &(scoreboard_table+i)->winsHome, &(scoreboard_table+i)->losesHome,
 &(scoreboard_table+i)->winsAway,&(scoreboard_table+i)->losesAway)!=EOF){

Moreover, you should give ear to the other comments like not using gets()

char fileName[40], *p;

fgets(fileName, sizeof fileName, stdin);
if ((p = strchr(fileName, '\n')) != NULL) { 
    *p = '\0'; /* remove newline */
}

By the way, an allocated memory is needed for char *name in the struct, it's the another reason for crashing, and not forget to free it.

  • Thank you. I realised that I forgot allocating memory for __char *name__. Can you tell me the reason why I should not be using `gets()`though? (I have just learned about strings in C a week ago.) Is it because `gets()` does not have any protection against people entering more characters than the char array can store? – PlagueTR May 08 '18 at 20:23
0

you have lot of problems in your code like.

Firstly, use fgets() instead of gets(). for e.g

fgets(fileName,sizeof(fileName),stdin);

Secondly, name is pointer member of scoreboard, allocate memory for it first. for e.g

scoreboard_table->name = malloc(SIZE); /* define SIZE */

Thirdly, fgetc() return type is int. check the manual page of fgetc(). So char curChar; should be int curChar;

Finally, in fscanf() while storing integers you need to provide the & address to each argument. for e.g

fscanf(inputFile,"%d",&(scoreboard_table+i)->games)

I try to explain in the comments. Here is the sample code

void Load_Scoreboard_Table(char *, scoreboard *);
int main(void){
        char fileName[40], *ret = NULL;
        FILE *inputFile;
        while (1){
                printf("Enter the file name> ");
                /* make sure fileName gets correctly stored in buffer as expected  */
                ret = fgets(fileName,sizeof(fileName),stdin); /* use fgets() instead of gets() */
                if(ret == NULL) { /* if failed, check again */
                        continue;
                }
                else {
                        printf("%s",ret); /* if fgets() result is as expected, control comes here */
                        fileName[strlen(fileName)-1] ='\0';
                }
                inputFile = fopen(fileName,"r");
                if (inputFile != NULL){
                        break;
                }
                printf("ERROR: The file %s could not be opened.\n",fileName);
                printf("Please verify that the file exists.\n");
        }
        int listLength=0;
        int curChar; /*return type of fgetc() is int */
        while ((curChar=fgetc(inputFile))!=EOF){
                if (curChar=='\n'){
                        listLength++;
                }
        }
        fclose(inputFile);
        scoreboard *scoreboard_table = malloc(sizeof(scoreboard) * listLength);/* no need to cast the result of malloc() */
        scoreboard_table->name = malloc(100);/*name is pointer member, allocate memory for it. must */
        Load_Scoreboard_Table(fileName,scoreboard_table);

        /* don't forget to free dynamically allocated memory here  @TODO */
        return 0;
}

void Load_Scoreboard_Table(char *fileName,scoreboard *scoreboard_table){
        FILE *inputFile = fopen(fileName,"r");
        if(inputFile == NULL ) {
                /* some mesage,, error handling  @TODO*/
        }
        int i=0;
        while (fscanf(inputFile,"%s %d %d %d %d %d", (scoreboard_table+i)->name,&(scoreboard_table+i)->games,&(scoreboard_table+i)->winsHome,&(scoreboard_table+i)->losesHome,&(scoreboard_table+i)->winsAway,&(scoreboard_table+i)->losesAway) > 0){
                (scoreboard_table+i)->winsTotal = (scoreboard_table+i)->winsHome + (scoreboard_table+i)->winsAway;
                (scoreboard_table+i)->losesTotal = (scoreboard_table+i)->losesHome + (scoreboard_table+i)->losesAway;
                (scoreboard_table+i)->totalPoints = (((scoreboard_table+i)->winsTotal)*2) + (scoreboard_table+i)->losesTotal;
                i++;
        }
        for(int j =0 ;j<i;j++) {
                printf("%d %d %d \n",(scoreboard_table+j)->winsTotal,(scoreboard_table+j)->losesTotal,(scoreboard_table+j)->totalPoints);
        }
}

From man 3 gets Why one shouldn't use gets() reason is here.

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

Achal
  • 11,821
  • 2
  • 15
  • 37
  • No, it's still wrong, dude. You need to compile with warnings turned on. You're not checking the return value of `fgets` and just assuming it succeeded. If it fails `fileName[strlen(fileName)-1] ='\0';` is undefined behavior. To test `echo -n "" | ./a.out` – MFisherKDX May 08 '18 at 20:15
  • keep something for OP ? I gave the enough hints. – Achal May 08 '18 at 20:17
  • Thank you for taking your time. I believe I understood your code; however when I compilted it. I got very similar results. The program __still freezes__ when I try to enter data.txt. – PlagueTR May 08 '18 at 20:20
  • *why down votes ? please mention the reason.* Already mentioned the reason in my comments. Not compiling with -Wall or ignoring the output -- which opens the posted code up to UB on crafted input. – MFisherKDX May 08 '18 at 20:33
  • Hi @PlagueTR I modified. check now. It should work, its working in my system. – Achal May 08 '18 at 20:37
  • I got your code to crash because you aren't checking the return value of `fgets`. *warning: ignoring return value of 'fgets', declared with attribute warn_unused_result [-Wunused_result]* gcc 7.2.0 – MFisherKDX May 08 '18 at 20:46
  • I compile with return value of `fgets()` @MFisherKDX ? check my answer. – Achal May 08 '18 at 20:46
  • And I used to compile any simple code this `gcc -Wall -Wstrict-prototypes -Werror`. As same I putted in my `.bash_aliases` – Achal May 08 '18 at 20:50
  • Sigh ... It's still wrong. If `fgets` fails you are still trying to `fopen` on uninitialized memory. :( – MFisherKDX May 08 '18 at 20:55
  • put the `else` part and check again. I just gave the hint. Its up to OP to check. – Achal May 08 '18 at 20:56
  • @achal Thank you. Your updated code seems to be working. However, it still freezes after printing the winstotal, losestotal, totalpoints variables. What could be causing this? I have included `string.h` as well since `strlen()` is found in `string.h`. – PlagueTR May 08 '18 at 22:55