#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#ifndef TEST_FILE_NAME
#define TEST_FILE_NAME "DPRINTF.TXT"
#endif
#define check(condition, message) \
do { \
if (!(condition)) { \
printf("%s: %s\n", message, #condition); \
(void)remove(TEST_FILE_NAME); \
exit(1); \
} \
} while (0)
#define STRING_PART \
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM" \
"NOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
static const char *strings[] = {
"test dprintf\n",
STRING_PART STRING_PART STRING_PART STRING_PART,
};
#define NSTRING (sizeof(strings) / sizeof(strings[0]))
int
main(void)
{
size_t s;
for (s = 0; s < NSTRING; s++) {
int fd = open(TEST_FILE_NAME, O_CREAT | O_WRONLY | O_TRUNC, 0666);
check(fd >= 0, "create file failed");
int ret = dprintf(fd, "%s", strings[s]);
check(ret >= 0 && (size_t)ret == strlen(strings[s]), "dprint failed");
close(fd);
FILE *f = fopen(TEST_FILE_NAME, "r");
static char buf[512];
check(f != NULL, "re-open file");
ret = fread(buf, sizeof(char), sizeof(buf) / sizeof(buf[0]), f);
check(ret >= 0 && (size_t)ret == strlen(strings[s]), "fread failed");
buf[ret] = '\0';
check(strcmp(buf, strings[s]) == 0, "fread contents incorrect");
fclose(f);
remove(TEST_FILE_NAME);
}
printf("test-dprintf success\n");
return 0;
}