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;
}
gcc, at a minimum use:-Wall -Wextra -Wconversion -pedantic -std=gnu11) Note other compilers use different options to produce the same results \$\endgroup\$char accum[CONT];this is a mighty large array to be placing on the stack. Suggest moving to 'file' scope (I.E. outside of any function \$\endgroup\$char *dates = malloc(sizeof(char *) * CONT);when calling any of the heap allocation functions:malloccallocrealloc, always check (!=NULL) the returned value to assure the operation was successful \$\endgroup\$getlin()strongly suggest including braces '{' and '}' around the body of thefor()statement \$\endgroup\$strcat(accum, line);the functionstrcat()searches for a NUL byte, then appends thelinebeginning at the NUL byte. However, the posted code does not set the first byte inaccum[]to '\0', so it is unknown where thelinewill actually be appended. This is undefined behavior and must be corrected \$\endgroup\$