Code:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/stat.h>
#include <time.h>
typedef struct TPayload *Payload;
struct TPayload {
int ftype; //type i.e. file or Dir
const char * fname; //name of file
const char * fpath; //path of file relative to root
int fsize; //size of file in bytes
time_t modtime; //time lat modified
};
typedef struct TCell *List;
struct TCell {
struct TCell * next;
Payload data;
};
//Initalises 1 element of the list
Payload initial(int filetype, const char * filename, const char * filepath, int filesize, time_t modifytime)
{
Payload p = (Payload)malloc(sizeof(struct TPayload));
p->ftype = filetype;
p->fname = filename;
p->fpath = filepath;
p->fsize = filesize;
p->modtime = modifytime;
printf("Payload intialsed successfully! \n");
return p;
}
//Construct the list
List cons(Payload p, List lp)
{
List res = (List) malloc(sizeof(struct TCell));
assert(res);
res->next = lp;
res->data = (Payload)malloc(sizeof(struct TPayload));
assert(res->data);
res->data->ftype = p->ftype;
assert(res->data->ftype);
res->data->fname = strdup(p->fname);
assert(res->data->fname);
res->data->fpath = strdup(p->fpath);
assert(res->data->fpath);
res->data->fsize = p->fsize;
assert(res->data->fsize);
res->data->modtime = p->modtime;
assert(res->data->modtime);
printf("list constructed ok\n");
return res;
}
void show(List lp)
{
char timestr[100];
for (; lp; lp = lp->next){
printf ("Type of file = %d\n",lp->data->ftype);
printf("Filename = %s\n",lp->data->fname);
printf("Path of file = %s\n",lp->data->fpath);
printf("Size of file = %d Bytes\n",lp->data->fsize);
strftime(timestr, 100, "%d-%m-%Y %H:%M:%S",localtime(&lp->data->modtime));
printf("Last modified on %s\n",timestr);
}
}
/***********Believe my problem is in insert function here *******/
/****************************************************************/
List insert( Payload p, List lp)
{
if ( lp == 0) return cons(p,lp);
if (strlen(p->fname) < strlen(lp->data->fname))
return cons(p, lp);
return cons(lp->data, insert(p, lp->next));
}
int main()
{
//Body of main not important only for testing functions
Payload p1 = initial(1,"file1","path1",10,10);
Payload p2 = initial(0,"file2","path2",20,20);
Payload p3 = initial(1,"file3","path3",30,30);
Payload p4 = initial(0,"file4","path4",40,40);
Payload p5 = initial(1,"file5","path5",50,50);
List lis1 = cons(p1,lis1);
show(lis1);
printf("test before insert\n");
lis1=insert(p1,lis1);
lis1=insert(p2,lis1);
lis1=insert(p3,lis1);
lis1=insert(p4,lis1);
lis1=insert(p5,lis1);
printf("test before show");
show(lis1);
return 0;
}
Any help be much appreciated.