aboutsummaryrefslogtreecommitdiff
path: root/lib/mlibc/tests/posix/getdelim.c
blob: bc43ef6164ff1305a5a3eda6d880e3407b1a43b6 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>

#ifdef USE_HOST_LIBC
#define TEST_FILE "getdelim-host-libc.tmp"
#else
#define TEST_FILE "getdelim.tmp"
#endif

int main(void) {
	FILE *fp;
	char *line = NULL;
	size_t len = 0;
	ssize_t read;

	// We have to open the file for writing and then reading separately,
	// as mlibc doesn't allow us to do both at the same time (yet).
	fp = fopen(TEST_FILE, "w");
	assert(fp);
	fputs("foo\nbar\nbaz\nquux\n", fp);
	fclose(fp);

	fp = fopen(TEST_FILE, "r");
	assert(fp);
	while ((read = getline(&line, &len, fp)) != -1) {
		printf("read line of length %zd, capacity %zu\n", read, len);
	}
	assert(!ferror(fp));
	free(line);
	fclose(fp);

	size_t nchars = 10000;
	fp = fopen(TEST_FILE, "w");
	assert(fp);
	for (size_t i = 0; i < nchars; i++)
		fputc('a', fp);
	fputc('b', fp);
	fclose(fp);

	line = NULL;
	len = 0;
	fp = fopen(TEST_FILE, "r");
	assert(fp);
	while ((read = getdelim(&line, &len, 'b', fp)) != -1) {
		printf("read line of length %zd, capacity %zu\n", read, len);
		assert((size_t)read == nchars + 1);
	}

	assert(len > nchars + 1);
	assert(!ferror(fp));
	assert(feof(fp));

	assert(getdelim(&line, &len, 'b', fp) == -1);
	assert(feof(fp));

	free(line);
	fclose(fp);

	fp = fopen(TEST_FILE, "w");
	assert(fp);
	assert(fwrite("1234ef\0f", 1, 8, fp) == 8);
	fclose(fp);

	fp = fopen(TEST_FILE, "r");
	assert(fp);

	/* test with line = NULL and large len */
	line = NULL;
	len = (size_t) ~0;
	assert(getdelim(&line, &len, 'e', fp) == 5);
	assert(!memcmp(line, "1234e", 6));
	assert(5 < len);

	/* test handling of internal nulls */
	assert(getdelim(&line, &len, 'e', fp) == 3);
	assert(!memcmp(line, "f\0f", 4));
	assert(3 < len);

	/* test handling of EOF */
	assert(getdelim(&line, &len, 'e', fp) == -1);

	free(line);
	fclose(fp);

	// Delete the file
	unlink(TEST_FILE);
}