#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
typedef struct student{
char name[25];
float marks;
}student_t;
int size = 0;
int capacity = 2;
char filename[30];
#define LINE_SIZE 128
void print(student_t **arr){
for (int i = 0; i < size; i++){
printf("%d: %s, %f\n", i+1, arr[i]->name, arr[i]->marks);
}
}
int create_table_entry(student_t **arr, int *size, int *capacity){
//printf("%d",size);
if( *size == *capacity) {
*capacity = *capacity * 2;
*arr = realloc (*arr, *capacity * sizeof(student_t));
}
return 0;
}
void add_record(student_t **arr, char *name, char *marks){
create_table_entry(arr,&size ,&capacity);
strcpy(arr[size]->name, name);
arr[size]->marks = atof(marks);
size++;
//print(arr);
}
int get_token(char *line, char fields[][30], char *delim) {
int token_cnt = 0;
char *token = strtok(line , delim);
while(token != NULL) {
// check if there is more than two tokens
if(token_cnt >= 2) {
return 3;
}
//printf("%s\n", token);
strcpy(fields[token_cnt++], token);
// update token
token = strtok(NULL, delim);
}
return token_cnt;
}
static void sort_data(){
// printf("reading the file ...........");
FILE *fileOpen = fopen( filename , "r");
if (fileOpen == NULL){
fprintf(stderr, "Error in opening input file. Filename = %s, Error = %s\n", filename, strerror(errno));
exit (-1);
}
char line[LINE_SIZE];
char fields [2][30];
student_t *arr;
arr = malloc(capacity * sizeof(student_t));
while(fgets(line, LINE_SIZE, fileOpen) != NULL){
int no_of_token = get_token(line, fields, ",");
// printf("%d\n",no_of_token);
if(no_of_token != 2){
//printf(" number of fields is not 2 for entry %d",j);
continue;
}
add_record(&arr,fields[0],fields[1]);
//printf("%s \n %s",fields[0],fields[1]);
}
print(&arr);
free(arr);
}
void check_argument(int argc,char *argv[]){
int count =0;
for(int i=1; i<argc; i++){
if(strstr("-f",argv[i])){
sprintf(filename,"%s",argv[i+1]);
count++;
}
}
if(count>1||count<1){
printf("invalid format");
}
//printf("%s\n",filename);
}
int main(int argc, char *argv[]){
check_argument(argc, argv);
sort_data();
return 0;
}
In the above program what i want to do is to open a (.csv)file read it line by line and then pass those line to the get_token function so token can be generated and i want only those line which have 2 fields i also want to get values of those 2 tokens so that i can pass it in add_record function and create a dynamic struct array so that i can sort it and store it in other file. but i am not getting the values of the student record in the file instead my output when i run it shows core dumped. so please help me with this problem as i am new to programming in c.And also sorry if my code hurt your eyes