Unit test stuff on new contact fields.
[libgcal.git] / utests / utils.c
blob2e922d68798016156097a1fbfbcbfe3fa1faf4d0
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <string.h>
7 #include <stdlib.h>
8 #include "utils.h"
10 int read_file(int fd, char **buffer, size_t *length)
12 int result = -1, bytes = 0;
13 size_t chunk = 256;
14 char *tmp = NULL;
16 *length = chunk + 1;
17 *buffer = (char *) malloc(*length);
18 if (!buffer)
19 goto exit;
21 while (((result = read(fd, (*buffer + bytes), chunk)) != -1) &&
22 (result != 0)) {
23 *length += chunk;
24 tmp = realloc(*buffer, *length + chunk);
25 if (!tmp) {
26 result = -1;
27 goto error;
29 *buffer = tmp;
30 bytes += result;
33 tmp[bytes] = '\0';
34 result = 0;
35 goto exit;
37 error:
38 free(*buffer);
39 *buffer = NULL;
41 exit:
42 return result;
46 char *find_file_path(char *file_name)
48 char *path, *tmp = NULL, *pos;
49 int len = 0;
50 path = getcwd(NULL, 0);
51 if (path == NULL)
52 printf("cannot get working directory!");
54 /* This should run in a subdirectory 'build' */
55 len = strrchr(path, '/') - path;
56 tmp = malloc(len + strlen(file_name) + 1);
58 pos = strstr(path, "build");
59 if (pos) {
60 --pos;
61 *pos = '\0';
64 strcpy(tmp, path);
65 strncat(tmp, file_name, len + strlen(file_name) + 1);
67 free(path);
68 return tmp;
73 int find_load_file(char *path, char **file_content)
75 int fd, res;
76 size_t len = 0;
77 char *file_name = path;
78 char *tmp;
80 tmp = find_file_path(file_name);
81 fd = open(tmp, O_RDONLY);
82 if (fd == -1) {
83 printf("cannot open XML file: Path = %s.\n",
84 tmp);
85 return -1;
88 res = read_file(fd, file_content, &len);
89 free(tmp);
90 close(fd);
92 return res;
95 int find_load_photo(char *path, char **file_content, size_t *length)
97 int fd, res;
98 char *file_name = path;
99 char *tmp;
101 tmp = find_file_path(file_name);
102 fd = open(tmp, O_RDONLY);
103 if (fd == -1) {
104 printf("cannot open photo file: Path = %s.\n",
105 tmp);
106 return -1;
109 res = read_file(fd, file_content, length);
110 free(tmp);
111 close(fd);
113 return res;