2023-12-04 15:05:54 +11:00

139 lines
2.6 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
int ID_OFFSET;
struct Game
{
int red;
int green;
int blue;
};
struct Games
{
struct Game games[100];
int interator;
};
void parse_game_data(char *line, struct Games games)
{
// printf("%s\n", line);
char *token;
const char delim[2] = ";";
token = strtok(line, delim);
printf("First token is: %s\n", token);
char *token2;
const char delim2[2] = ",";
token2 = strtok(token, delim2);
printf("Second token is: %s\n", token2);
struct Game tmpGame;
}
int str_to_int(char *str)
{
int result;
char *tmp;
result = strtol(str, &tmp, 10);
return result;
}
int get_id(char *ptr)
{
int id;
char *_id = (char *)malloc(4);
for (int i = 0; i <= 4; i++)
{
if (ptr[i] != ':')
{
_id[i] = ptr[i];
}
else
{
ID_OFFSET = i;
break;
}
}
id = str_to_int(_id);
return id;
}
int main()
{
struct Games games;
int MAX_RED = 12;
int MAX_GREEN = 13;
int MAX_BLUE = 14;
int GAME_OFFSET = 5; // Skip the word Game and start on the ID number
const char *inputFile = "input";
int fd = open(inputFile, O_RDONLY);
if (fd < 0)
{
printf("\n\"%s \" could not open\n");
exit(1);
}
struct stat statbuf;
int err = fstat(fd, &statbuf);
if (err < 0)
{
printf("\n\"%s \" could not open\n", inputFile);
exit(2);
}
char *ptr = mmap(NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED)
{
printf("Mapping failed");
return 1;
}
int inLine = 0;
for (int i = 0; i < statbuf.st_size; i++)
{
int id;
char *tmpLine = (char *)malloc(255);
for (int j = 0; j < __INT64_MAX__; j++)
{
if (inLine == 0)
{
inLine = 1;
i += GAME_OFFSET;
id = get_id(&ptr[i]);
i += ID_OFFSET + 1;
continue;
}
if (ptr[i + j] == '\n')
{
memcpy(tmpLine, &ptr[i], j);
printf("ID: %i |", id);
parse_game_data(tmpLine, games);
i += j;
break;
}
tmpLine[j] = ptr[i + j];
}
inLine = 0;
}
err = munmap(ptr, statbuf.st_size);
if (err != 0)
{
printf("Unmapping failed");
return 1;
}
return 0;
}