conn: initialize conn struct correctly
[pop3.git] / uidl.c
blobe26d1b23457db198527cf4d147bd4b184f5c5c13
1 #include <fcntl.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include "uidl.h"
9 static int file_size(int fd)
11 struct stat st;
12 fstat(fd, &st);
13 return st.st_size;
16 static int xread(int fd, char *buf, int len)
18 int nr = 0;
19 while (nr < len) {
20 int cr = read(fd, buf + nr, len - nr);
21 if (cr == -1)
22 break;
23 nr += cr;
25 return nr;
28 struct uidl *uidl_read(char *filename)
30 struct uidl *uidl = malloc(sizeof(*uidl));
31 int len;
32 uidl->fd = open(filename, O_RDWR | O_CREAT, 0600);
33 len = file_size(uidl->fd);
34 lseek(uidl->fd, 0, SEEK_SET);
35 uidl->txt = malloc(len + 1);
36 xread(uidl->fd, uidl->txt, len);
37 uidl->txt[len] = '\0';
38 lseek(uidl->fd, 0, SEEK_END);
39 return uidl;
42 static char *putnl(char *dst, char *src)
44 while (*src)
45 *dst++ = *src++;
46 *dst++ = '\n';
47 *dst = '\0';
48 return dst;
51 int uidl_find(struct uidl *uidl, char *id)
53 char kw[128];
54 putnl(kw, id);
55 return !!strstr(uidl->txt, kw);
58 void uidl_add(struct uidl *uidl, char *id)
60 char kw[128];
61 int len = putnl(kw, id) - kw;
62 write(uidl->fd, kw, len);
65 void uidl_save(struct uidl *uidl)
67 close(uidl->fd);
68 free(uidl->txt);
69 free(uidl);