aboutsummaryrefslogtreecommitdiff
path: root/lib/mlibc/tests/posix/open_memstream.c
blob: 03470030b946963f28992879fbfca3d79e6a5de5 (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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define WRITE_NO 1024

int main() {
	size_t size;
	char *buf;

	FILE *fp = open_memstream(&buf, &size);
	assert(fp);

	char c = 'A';
	for (size_t i = 0; i < WRITE_NO; i++)
		assert(fwrite(&c, sizeof(char), 1, fp) == 1);

	// Flush the file to update the pointers.
	assert(!fflush(fp));

	assert(size == WRITE_NO);
	for (size_t i = 0; i < size; i++)
		assert(buf[i] == c);

	// Check if the stream maintains a null-bye at the end.
	assert(buf[size] == '\0');

	// Stream should be expanded, size should be == 2*WRITE_NO.
	assert(!fseek(fp, WRITE_NO, SEEK_END));
	assert(!fflush(fp));
	assert(size == 2*WRITE_NO);
	assert(buf[size] == '\0');

	// Check if it's filled with zero's.
	for (size_t i = WRITE_NO; i < size; i++)
		assert(buf[i] == '\0');

	// Go back and overwrite the 0's with 'B'.
	assert(!fseek(fp, -WRITE_NO, SEEK_CUR));
	c = 'B';
	for (size_t i = 0; i < WRITE_NO; i++)
		assert(fwrite(&c, sizeof(char), 1, fp) == 1);

	// Check if that happened.
	assert(size == 2*WRITE_NO);
	for (size_t i = WRITE_NO; i < size; i++)
		assert(buf[i] == c);
	assert(buf[size] == '\0');

	// Go to the front and write 'B'.
	assert(!fseek(fp, 0, SEEK_SET));
	for (size_t i = 0; i < WRITE_NO; i++)
		assert(fwrite(&c, sizeof(char), 1, fp) == 1);

	// Check if that happened.
	assert(size == 2*WRITE_NO);
	for (size_t i = 0; i < size; i++)
		assert(buf[i] == c);
	assert(buf[size] == '\0');

	// Close the file, we have tested everything.
	assert(!fclose(fp));
	free(buf);
	return 0;
}