|
| 1 | +/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ |
| 2 | +│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ |
| 3 | +╞══════════════════════════════════════════════════════════════════════════════╡ |
| 4 | +│ Copyright 2021 Justine Alexandra Roberts Tunney │ |
| 5 | +│ │ |
| 6 | +│ Permission to use, copy, modify, and/or distribute this software for │ |
| 7 | +│ any purpose with or without fee is hereby granted, provided that the │ |
| 8 | +│ above copyright notice and this permission notice appear in all copies. │ |
| 9 | +│ │ |
| 10 | +│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ |
| 11 | +│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ |
| 12 | +│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ |
| 13 | +│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ |
| 14 | +│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ |
| 15 | +│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ |
| 16 | +│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ |
| 17 | +│ PERFORMANCE OF THIS SOFTWARE. │ |
| 18 | +╚─────────────────────────────────────────────────────────────────────────────*/ |
| 19 | +#include "libc/stdio/stdio.h" |
| 20 | +#include "libc/testlib/testlib.h" |
| 21 | + |
| 22 | +/* |
| 23 | + * This test was contributed by @ahgamut |
| 24 | + * https://github.com/jart/cosmopolitan/issues/61#issuecomment-792214575 |
| 25 | + */ |
| 26 | + |
| 27 | +char testlib_enable_tmp_setup_teardown; |
| 28 | + |
| 29 | +int writefile(const char* filename) { |
| 30 | + int stat = 0; |
| 31 | + FILE* fp = fopen(filename, "w"); |
| 32 | + stat = fputs("cosmopolitan libc\n", fp); |
| 33 | + fclose(fp); |
| 34 | + return stat; |
| 35 | +} |
| 36 | + |
| 37 | +int readfile(const char* filename) { |
| 38 | + int stat = 0; |
| 39 | + char buf1[30]; |
| 40 | + char buf2[30]; |
| 41 | + FILE *fp1, *fp2; |
| 42 | + fp1 = fopen(filename, "r"); |
| 43 | + if (!fp1) { |
| 44 | + printf("failed to read %s in r\n", filename); |
| 45 | + return 1; |
| 46 | + } |
| 47 | + buf1[0] = fgetc(fp1); |
| 48 | + buf1[1] = '\0'; |
| 49 | + fp2 = freopen(filename, "rb", fp1); |
| 50 | + if (!fp2) { |
| 51 | + printf("failed to read %s in rb\n", filename); |
| 52 | + return 1; |
| 53 | + } |
| 54 | + stat = fread(buf2, sizeof(buf2[0]), 20, fp2); |
| 55 | + ASSERT_EQ(18, stat); |
| 56 | + buf2[stat] = '\0'; |
| 57 | + fclose(fp2); |
| 58 | + ASSERT_STREQ("c", buf1); |
| 59 | + ASSERT_STREQ("cosmopolitan libc\n", buf2); |
| 60 | + return 0; |
| 61 | +} |
| 62 | + |
| 63 | +TEST(freopen, test) { |
| 64 | + writefile("file.txt"); |
| 65 | + readfile("file.txt"); |
| 66 | +} |
0 commit comments