lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* Test for ungetc bugs. */ |
| 2 | |
| 3 | #include <stdio.h> |
| 4 | #include <unistd.h> |
| 5 | |
| 6 | #undef assert |
| 7 | #define assert(x) \ |
| 8 | if (!(x)) \ |
| 9 | { \ |
| 10 | fputs ("test failed: " #x "\n", stderr); \ |
| 11 | retval = 1; \ |
| 12 | goto the_end; \ |
| 13 | } |
| 14 | |
| 15 | int |
| 16 | main (int argc, char *argv[]) |
| 17 | { |
| 18 | char *name; |
| 19 | FILE *fp = NULL; |
| 20 | int retval = 0; |
| 21 | int c; |
| 22 | char buffer[64]; |
| 23 | |
| 24 | name = tmpnam (NULL); |
| 25 | fp = fopen (name, "w"); |
| 26 | assert (fp != NULL) |
| 27 | fputs ("bla", fp); |
| 28 | fclose (fp); |
| 29 | fp = NULL; |
| 30 | |
| 31 | fp = fopen (name, "r"); |
| 32 | assert (fp != NULL); |
| 33 | assert (ungetc ('z', fp) == 'z'); |
| 34 | assert (getc (fp) == 'z'); |
| 35 | assert (getc (fp) == 'b'); |
| 36 | assert (getc (fp) == 'l'); |
| 37 | assert (ungetc ('m', fp) == 'm'); |
| 38 | assert (getc (fp) == 'm'); |
| 39 | assert ((c = getc (fp)) == 'a'); |
| 40 | assert (getc (fp) == EOF); |
| 41 | assert (ungetc (c, fp) == c); |
| 42 | assert (feof (fp) == 0); |
| 43 | assert (getc (fp) == c); |
| 44 | assert (getc (fp) == EOF); |
| 45 | fclose (fp); |
| 46 | fp = NULL; |
| 47 | |
| 48 | fp = fopen (name, "r"); |
| 49 | assert (fp != NULL); |
| 50 | assert (getc (fp) == 'b'); |
| 51 | assert (getc (fp) == 'l'); |
| 52 | assert (ungetc ('b', fp) == 'b'); |
| 53 | assert (fread (buffer, 1, 64, fp) == 2); |
| 54 | assert (buffer[0] == 'b'); |
| 55 | assert (buffer[1] == 'a'); |
| 56 | |
| 57 | the_end: |
| 58 | if (fp != NULL) |
| 59 | fclose (fp); |
| 60 | unlink (name); |
| 61 | |
| 62 | return retval; |
| 63 | } |