1/* Test case by Yoshito Kawada <KAWADA@jp.ibm.com>.  */
2#include <errno.h>
3#include <fcntl.h>
4#include <locale.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <unistd.h>
9#include <wchar.h>
10
11
12void error(int exitCode, int, const char* message);
13
14
15int
16main(int argc, char *argv[])
17{
18	int a = 3;
19	int fd;
20	char name[] = "/tmp/wprintf.out.XXXXXX";
21	FILE *fp;
22	char buf[100];
23	size_t len;
24	int res = 0;
25
26	fd = mkstemp(name);
27	if (fd == -1)
28		error(EXIT_FAILURE, errno, "cannot open temporary file");
29
30	unlink(name);
31
32	setlocale(LC_ALL, "");
33
34	fp = fdopen(dup(fd), "w");
35	if (fp == NULL)
36		error(EXIT_FAILURE, errno, "fdopen(,\"w\")");
37
38	fwprintf(fp,L"test start" );
39	fwprintf(fp, L" int %d\n", a);
40
41	/* String with precision.  */
42	fwprintf(fp, L"1[%6.3s]\n", argv[1]);
43
44	fclose(fp);
45
46	fp = fdopen(dup (fd), "a");
47	if (fp == NULL)
48		error(EXIT_FAILURE, errno, "fdopen(,\"a\")");
49
50	setvbuf(fp, NULL, _IONBF, 0);
51
52	/* fwprintf to unbuffered stream.   */
53	fwprintf(fp, L"hello.\n");
54
55	fclose(fp);
56
57	/* Now read it back in.  This time using multibyte functions.  */
58	lseek(fd, SEEK_SET, 0);
59	fp = fdopen(fd, "r");
60	if (fp == NULL)
61		error(EXIT_FAILURE, errno, "fdopen(,\"r\")");
62
63	if (fgets(buf, sizeof buf, fp) != buf)
64		error(EXIT_FAILURE, errno, "first fgets");
65	len = strlen(buf);
66	if (buf[len - 1] == '\n')
67		--len;
68	else {
69		puts ("newline missing after first line");
70		res = 1;
71	}
72	printf("1st line: \"%.*s\" -> %s\n", (int) len, buf,
73		strncmp(buf, "test start int 3", len) == 0 ? "OK" : "FAIL");
74	res |= strncmp(buf, "test start int 3", len) != 0;
75
76	if (fgets(buf, sizeof(buf), fp) != buf)
77		error(EXIT_FAILURE, errno, "second fgets");
78	len = strlen(buf);
79	if (buf[len - 1] == '\n')
80		--len;
81	else {
82		puts("newline missing after second line");
83		res = 1;
84	}
85	printf ("2nd line: \"%.*s\" -> %s\n", (int) len, buf,
86		strncmp(buf, "1[   Som]", len) == 0 ? "OK" : "FAIL");
87	res |= strncmp(buf, "1[   Som]", len) != 0;
88
89	if (fgets(buf, sizeof(buf), fp) != buf)
90		error(EXIT_FAILURE, errno, "third fgets");
91	len = strlen(buf);
92	if (buf[len - 1] == '\n')
93		--len;
94	else {
95		puts("newline missing after third line");
96		res = 1;
97	}
98	printf("3rd line: \"%.*s\" -> %s\n", (int) len, buf,
99		strncmp(buf, "hello.", len) == 0 ? "OK" : "FAIL");
100	res |= strncmp(buf, "hello.", len) != 0;
101
102	return res;
103}
104
105
106void
107error(int exitCode, int errorCode, const char* message)
108{
109	perror(message);
110	exit(exitCode);
111}
112