I am writing a program where I have to read data from a file and then sort them in descending ascending order. I am having trouble with the sorting part of it. How do I sort the float values and then print the struct sorted? Here is my code. I keep getting a segmentation fault. I am not sure how to fix it.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef struct importedData {
char type[100];
float literAmount;
int miles;
char color[20];
}DATA;
void sorting();
int main() {
int userInput;
//initialize();
DATA *data = NULL;
sorting(data);
//Do while loop to loop through menu until exit.
do {
//Print statements to put out the output options
printf("Choose the option you would like to preform \n");
printf("1.Sort data from the float value & print high to low \n2.Sort data by the float value & print low to high\n3.Sort data by the int value & print high to low\n4.Sort data by the int value & print low to high");
scanf("%d", &userInput); //Scanner to take in the keyboard input
} while (userInput != 5);
return 0;
}
int numberOfLines() {
FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
int c = 0; //Count the number of characters
int count = 0; //Number of lines
if(fp == NULL) { //If file was not able to be opened program will exit
printf("Unable to read file. Closing");
return 0;
}
while((c = fgetc(fp)) != EOF) { //Get the character and make sure it isnt the END OF FILE
if(c == '\n') { //If the charcter is set to \n (New Line) will add one to counter
count++;
}
}
fclose(fp);
return count;
}
DATA* initialize(DATA *data) {
data = malloc(numberOfLines() * sizeof(*data));
FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
int counter = 0;
int totalIterations = numberOfLines();
while(counter < totalIterations) {
if(fscanf(fp, "%s %f %d %s\n", data[counter].type, &data[counter].literAmount, &data[counter].miles, data[counter].color) !=4) {
}
printf("data stored is: %s %f %d %s\n", data[counter].type, data[counter].literAmount, data[counter].miles, data[counter].color);
}
return (data);
}
void sorting() {
DATA *data = malloc(numberOfLines() * sizeof(*data));
FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
int counter = 0;
int totalIterations = numberOfLines();
while(counter < totalIterations) {
if(fscanf(fp, "%s %f %d %s\n", data[counter].type, &data[counter].literAmount, &data[counter].miles, data[counter].color) ==4) {
counter++;
}
}
DATA *temp;
int i, j;
for(i = 0; i < (numberOfLines() -1); i++) {
for(j = 0; j < (numberOfLines() -1); j++) {
if(data[i].literAmount > data[i+1].literAmount) {
data[i].literAmount = (*temp).literAmount;
printf("Temp: %f", (*temp).literAmount);
}
}
}
}
scanf()the wrong way, it has a return value, do not ignore it. Have you triedqsort()?while (counter < totalIterations). Just usewhile (fscanf(...) != 4)and the format string can be"%s%f%d%s\n", the spaces are not needed. And return does not need parentheses.