Actually all the filenames are hard coded. So make a file date.txt with the following data in the directory where the program is....
24 may 2010
12 aug 2007
12 aug 2006
15 aug 2006
07 aug 2006
12 aug 2005
24 may 2003
Before running the code below take the backup of the above file.
#include<stdio.h>
#include<string.h>
void parse_date(char *, int *, char *, int *, int *);
void sort_date(int, char *, int, int);
int main()
{
FILE *fp;
char ch, dstr[20], month[5];
int i=0, dd, mm, yy, j;
fp=fopen("date.txt", "r");
while((ch=fgetc(fp)) != EOF)
{
if(ch != '\n')
{
dstr[i++]=ch;
continue;
}
dstr[i]='\0';
parse_date(dstr, &dd, month, &mm, &yy);
sort_date(dd, month, mm, yy);
i=0;
}
fclose(fp);
remove("date.txt");
rename("date1.txt", "date.txt");
return 0;
}
void parse_date(char *dstr, int *dd, char *month, int *mm, int *yy)
{
char temp[5], mon[12][5]={"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sept", "oct", "nov", "dec"};
int i, j;
j=0;
i=0;
while(dstr[i] != ' ') /* This loop will give the day */
temp[j++]=dstr[i++];
temp[j]='\0';
*dd=atoi(temp);
j=0;
i++;
while(dstr[i] != ' ') /* This loop will give the month */
month[j++]=dstr[i++];
month[j]='\0';
for(j=0; j<12; j++)
{
if(strcasecmp(month, mon[j]) == 0)
{
*mm=j+1;
break;
}
}
j=0;
i++;
while(dstr[i] != '\0') /* This loop will give the year */
temp[j++]=dstr[i++];
temp[j]='\0';
*yy=atoi(temp);
}
void sort_date(int dd, char *month, int mm, int yy)
{
static int flag1;
FILE *fp, *ft;
char ch, dstr[20], month1[5];
int i=0, flag2, dd1, mm1, yy1;
if(flag1 == 0)
{
fp=fopen("date1.txt", "w");
fprintf(fp, "%d %s %d\n", dd, month, yy);
fclose(fp);
flag1=1;
}
else
{
flag2=0;
fp=fopen("date1.txt", "r");
ft=fopen("temp.txt", "w");
while((ch=fgetc(fp)) != EOF)
{
if(ch != '\n')
{
dstr[i++]=ch;
continue;
}
dstr[i]='\0';
if(flag2 == 0)
{
parse_date(dstr, &dd1, month1, &mm1, &yy1);
if(yy < yy1)
flag2=1;
else if(mm < mm1 && yy == yy1)
flag2=1;
else if(dd < dd1 && mm == mm1 && yy == yy)
flag2=1;
if(flag2 == 1)
fprintf(ft, "%d %s %d\n", dd, month, yy);
fprintf(ft, "%s\n", dstr);
}
else
fprintf(ft, "%s\n", dstr);
i=0;
}
if(flag2 == 0)
fprintf(ft, "%d %s %d\n", dd, month, yy);
fclose(fp);
fclose(ft);
remove("date1.txt");
rename("temp.txt", "date1.txt");
}
}