uidl: use snprintf instead of putnl
[pop3.git] / uidl.c
blob8ceb2936870ba2e7af6562c0f2e6925ac3077b46
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include "uidl.h"
10 static int file_size(int fd)
12 struct stat st;
13 fstat(fd, &st);
14 return st.st_size;
17 static int xread(int fd, char *buf, int len)
19 int nr = 0;
20 while (nr < len) {
21 int cr = read(fd, buf + nr, len - nr);
22 if (cr == -1)
23 break;
24 nr += cr;
26 return nr;
29 struct uidl *uidl_read(char *filename)
31 struct uidl *uidl = malloc(sizeof(*uidl));
32 int len;
33 uidl->fd = open(filename, O_RDWR | O_CREAT, 0600);
34 len = file_size(uidl->fd);
35 lseek(uidl->fd, 0, SEEK_SET);
36 uidl->txt = malloc(len + 1);
37 xread(uidl->fd, uidl->txt, len);
38 uidl->txt[len] = '\0';
39 lseek(uidl->fd, 0, SEEK_END);
40 return uidl;
43 int uidl_find(struct uidl *uidl, char *id)
45 char kw[256];
46 snprintf(kw, sizeof(kw), "%s\n", id);
47 return !!strstr(uidl->txt, kw);
50 void uidl_add(struct uidl *uidl, char *id)
52 char kw[256];
53 snprintf(kw, sizeof(kw), "%s\n", id);
54 write(uidl->fd, kw, strlen(kw));
57 void uidl_save(struct uidl *uidl)
59 close(uidl->fd);
60 free(uidl->txt);
61 free(uidl);