Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Read
{
char str1[64];
int year;
char type[64];
char str2[64];
} read;
void remove_new_line(char*);
int main(int argc, char *argv[])
{
FILE *fp = NULL;
char line[256];
char* token;
int i = 0;
char input[50];
char command[50];
char val1[30];
char val2[30];
read info[8];
if (argc <= 1)
{
printf("The file does not exist\n");
return 0;
}
fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf("No File Exists\n");
return 0;
}
while (fgets(line, sizeof(line), fp))
{
remove_new_line(line);
token = strtok(line, ",");
strcpy(info[i].str1, token);
token = strtok(NULL, ",");
info[i].year = atoi(token);
token = strtok(NULL, ",");
strcpy(info[i].type, token);
token = strtok(NULL, ",");
strcpy(info[i++].str2, token);
}
while (1)
{
scanf(" %49[^\n]s", input);
fflush(stdin);
command[0] = 0;
val1[0] = 0;
val2[0] = 0;
sscanf(input, "%s, %s, %s", command, val1, val2);
if (strcmp(command, "SORT") == 0)
{
printf("%s | %d | %s | %s\n", info[0].str1, info[0].year, info[0].type, info[0].str2);
}
else if (strcmp(command, "QUIT") == 0)
{
exit(0);
}
break;
}
return 0;
}
void remove_new_line(char* str)
{
char* p;
if (p = strchr(str, '\n'))
{
*p = '\0';
}
}
And the text file is:
Dive,2011,Electronic,Tycho
Portraits,2015,Electronic,Maribou State
Mer De Noms,2000,Hard Rock,A Perfect Circle
Awake,2014,Electronic,Tycho
Epoch,2016,Electronic,Tycho
Farewell,2016,Chamber,Cicada
The Beatles,1968,Rock,The Beatles
Sines,2014,Post-Metal,Jakob
What I want to do is to make a variable named "column" and store info[0~3].str1 in column[0], and info[0~3].year in column[1] and so on. This is for the later work, which is to select column that I want to sort in an ascending order (or descending order) through calling strcmp function.