I have the following task:
Implement a program that reads lines of data from a file specified as a command-line argument, having the following format:
Code:
{ana12 : mere}
{andrew : -}
{john : student}
{michael : teacher}
The fields are separated by an ':' character and might have an arbitrary number of spaces in between. The following constraints should be taken into consideration and validated:
- key must be a word up to 50 characters, composed only of letters or digits;
- value can be an arbitrarily long word, composed of letters or '_' character.
Print the data from the file in descending order of the key length, breaking ties by ordering the keys in lexicographical order.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 51
#define CHUNK 300
int main(int argc, char* argv[])
{
if(argc != 2)
{
printf("Invalid format.\n");
return -1;
}
FILE* fin = fopen(argv[1], "rt");
if(!fin)
{
printf("Error opening the file.\n");
return 1;
}
char key[MAX];
char* s = calloc(CHUNK, sizeof(char));
while(fgets(s, CHUNK, fin))
{
char *token = strtok(s, ":");
while(token)
{
while(sscanf(token, "%50s", key) == 1)
{
int len = strlen(key), ch;
//if(key[0] ==
printf("Key : %s\n", key);
}
token = strtok(NULL, ":");
}
}
fclose(fin);
return 0;
}
I'm having trouble with these kind of tasks because I know I need to use structures and sort the data but I'm a bit lost. The code above is stuck in an infinite loop and prints: Could just give me some steps to work on, like what structure should I implement and how to sort the data? Thanks in advance!