File: getaddrsfromfd.c

package info (click to toggle)
mlmmj 1.2.17-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,836 kB
  • ctags: 585
  • sloc: ansic: 8,973; sh: 4,521; php: 1,057; perl: 643; makefile: 156
file content (60 lines) | stat: -rw-r--r-- 1,427 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#include "mlmmj.h"
#include "log_error.h"
#include "memory.h"
#include "strgen.h"
#include "getaddrsfromfd.h"

off_t getaddrsfromfd(struct strlist *slist, int fd, int max)
{
	off_t offset = lseek(fd, 0, SEEK_CUR);
	char *start, *cur, *next;
	struct stat st;
	size_t len;

	if(fstat(fd, &st) < 0) {
		log_error(LOG_ARGS, "Could not fstat fd");
		return -1;
	}
	/* mmap of 0-bytes is invalid */
	if(st.st_size == 0) {
		return 0;
	}

	start = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
	if(start == MAP_FAILED) {
		log_error(LOG_ARGS, "Could not mmap fd");
		return -1;
	}
	
	for(next = cur = (start + offset); next < start + st.st_size; next++) {
		if(*next == '\n' || next == start + st.st_size - 1) {
			slist->count++;
			len = next - cur;
			if(next == start + st.st_size - 1 && *next != '\n')
				len++;
			slist->strs = (char **)myrealloc(slist->strs,
					sizeof(char *) * slist->count);
			slist->strs[slist->count - 1] = mymalloc(len + 1);
			strncpy(slist->strs[slist->count - 1], cur, len);
			slist->strs[slist->count - 1][len] = '\0';
			cur = next + 1;
		} else {
			continue;
		}
		if(slist->count >= max) {
			offset = (off_t)(cur - start);
			goto donegetting;
		}
	}
	offset = st.st_size;
donegetting:			
	munmap(start, st.st_size);
	lseek(fd, offset, SEEK_SET);
	return st.st_size - offset;
}