Skip to main content
1 of 2

Getting from text and format the date

The task is find by pattern d--m--y---- all occurrences in text, reformat it to yyyy:mm:dd and print it separately from initial text. Actually I done all except formatting. And even in my written code I have some doubts because I just begun to learn this language. Maybe someone would help me and say what's wrong with my code and how to finish that task on a better way. Any comments are appreciated.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXLINE 1000
#define CONT 1000000

int getlin(char *, int);
int pickDates(char *, char *);
int isDate(char *, int);

int main() 
{
    int len;
    char line[MAXLINE];
    char accum[CONT];
    char *dates = malloc(sizeof(char *) * CONT);

    while ((len = getlin(line, MAXLINE)) > 0)
        strcat(accum, line);

    pickDates(dates, accum);
    printf("%s\n", dates);
    
    free(dates);

    return 0;
}

int getlin(char *s, int lim) {
    int i, c, j = 0;

    for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
    if (i < lim - 2) 
    {
        s[j] = c;
        ++j;
    }
    if (c == '\n')
    {
        s[j] = c;
        ++i;
        ++j;
    }
    s[j] = '\0';
    
    return i;
}

int pickDates(char *dates, char *cont)
{
    int j = 0;
    const char *template = "d--m--y----";
    char *date;
    int temp_len = strlen(template);

    for (int i = 0; i < strlen(cont); i++)
        if (cont[i] == template[0] && cont[i+3] == template[3] && cont[i+6] == template[6])
        {
            date = malloc(sizeof(char) * temp_len);
            memcpy(date, &cont[i], temp_len);
            if (isDate(date, temp_len))
            {
                j += 8;
                strcat(dates, date);
            }
            free(date);
        }

    dates = realloc(dates, sizeof(char) * j);
    
    return 0;
}

int isDate(char *date_str, int len)
{
    int i = 0;
    int dd = atoi(&date_str[i+1]);
    int mm = atoi(&date_str[i+4]);
    int yy = atoi(&date_str[i+7]);
    char tmp[5] = {'0'};

    memset(date_str, 0, len - 3);
    date_str = realloc(date_str, sizeof(char) * (len - 3));

    if (dd < 32 && dd > 0 && mm < 13 && mm > 0 && yy > 0)
    {
        sprintf(tmp, "%04d", yy);
        strcat(date_str, tmp);
        sprintf(tmp, "%02d", mm);
        strcat(date_str, tmp);
        sprintf(tmp, "%02d", dd);
        strcat(date_str, tmp);

        return 1;
    }
    else return -1;
}