xref: /haiku/src/tests/system/libroot/posix/tst-ungetwc2.c (revision 8ce2ca0fc7eec2be8c69a84aaa7883c9824d1a7e)
1 /* Taken from the Li18nux base test suite.  */
2 
3 #define _XOPEN_SOURCE 500
4 #include <locale.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <wchar.h>
9 
10 
11 int
main(void)12 main(void)
13 {
14 	FILE *fp;
15 	const char *str = "abcdef";
16 	wint_t ret, wc;
17 	char fname[] = "/tmp/tst-ungetwc2.out.XXXXXX";
18 	int fd;
19 	long int pos;
20 	int result = 0;
21 
22 	puts("This program runs on de_DE.UTF-8 locale.");
23 	if (setlocale(LC_ALL, "de_DE.UTF-8") == NULL) {
24 		fprintf(stderr, "Err: Cannot run on the de_DE.UTF-8 locale\n");
25 		exit(EXIT_FAILURE);
26 	}
27 
28 	/* Write some characters to `testfile'. */
29 	fd = mkstemp(fname);
30 	if (fd == -1) {
31 		printf("cannot open temp file: %m\n");
32 		exit(EXIT_FAILURE);
33 	}
34 	if ((fp = fdopen(fd, "w")) == NULL) {
35 		fprintf(stderr, "Cannot open 'testfile'.\n");
36 		exit(EXIT_FAILURE);
37 	}
38 	fputs(str, fp);
39 	fclose(fp);
40 
41 	/* Open `testfile'. */
42 	if ((fp = fopen(fname, "r")) == NULL) {
43 		fprintf(stderr, "Cannot open 'testfile'.");
44 		exit(EXIT_FAILURE);
45 	}
46 
47 	/* Get a character. */
48 	wc = getwc(fp);
49 	pos = ftell(fp);
50 	printf("After get a character: %ld\n", pos);
51 	if (pos != 1)
52 		result = 1;
53 
54 	/* Unget a character. */
55 	ret = ungetwc(wc, fp);
56 	if (ret == WEOF) {
57 		fprintf(stderr, "ungetwc() returns NULL.");
58 		exit(EXIT_FAILURE);
59 	}
60 	pos = ftell(fp);
61 	printf("After unget a character: %ld\n", pos);
62 	if (pos != 0)
63 		result = 1;
64 
65 	/* Reget a character. */
66 	wc = getwc(fp);
67 	pos = ftell(fp);
68 	printf("After reget a character: %ld\n", pos);
69 	if (pos != 1)
70 		result = 1;
71 
72 	fclose(fp);
73 
74 	unlink(fname);
75 
76 	return result;
77 }
78