summaryrefslogtreecommitdiff
path: root/lib/mlibc/tests/ansi/ungetc.c
blob: 8773c6dbbb6a35487a18c71d85054212740a2d32 (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
#include <stdio.h>
#include <assert.h>

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

void test(int buffering) {
	FILE *f = fopen(TEST_FILE, "w");
	for(int c = '0'; c <= '9'; c++) {
		fputc(c, f);
	}
	fclose(f);

	f = fopen(TEST_FILE, "r");
	if (!buffering) {
		setbuf(f, NULL);
	}

	assert(ungetc('x', f) == 'x');
	assert(fgetc(f) == 'x');

	// Test pushing back the same character
	for (int c = '0'; c <= '9'; c++) {
		assert(fgetc(f) == c);
		assert(ungetc(c, f) == c);
		assert(fgetc(f) == c);
	}
	assert(fgetc(f) == EOF);
	assert(ungetc(EOF, f) == EOF);

	// Even though the spec does not guarantee it, we should be able to
	// ungetc more than one character.
	assert(ungetc('x', f) == 'x');
	assert(ungetc('y', f) == 'y');
	assert(fgetc(f) == 'y');
	assert(fgetc(f) == 'x');

	// Seeking should discard the effects of ungetc.
	assert(ungetc('x', f) == 'x');
	rewind(f);

	// Test pushing back a different character
	for (int c = '0'; c <= '9'; c++) {
		assert(fgetc(f) == c);
		assert(ungetc(c - '0' + 'a', f) == c - '0' + 'a');
		assert(fgetc(f) == c - '0' + 'a');
	}

#ifndef USE_HOST_LIBC
	// Too many ungetcs should fail.
	int eof = 0;
	for (int i = 0; i < 100; i++) {
		if (ungetc('x', f) == EOF) {
			eof = 1;
			break;
		}
	}
	assert(eof);
#endif

	fclose(f);

	// TODO: Test with other operations, like fread.
}

int main() {
	fprintf(stderr, "with buffering...\n");
	test(1);
	fprintf(stderr, "without buffering...\n");
	test(0);
}