File: getaddrsfromfd.c

package info (click to toggle)
mlmmj 1.2.11-7.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,020 kB
  • ctags: 439
  • sloc: ansic: 7,225; sh: 4,030; php: 727; perl: 481; makefile: 176
file content (56 lines) | stat: -rw-r--r-- 1,355 bytes parent folder | download | duplicates (3)
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
#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;
	}

	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;
}