diff options
author | Alon Zakai <alonzakai@gmail.com> | 2013-07-29 10:43:23 -0700 |
---|---|---|
committer | Alon Zakai <alonzakai@gmail.com> | 2013-07-29 10:43:23 -0700 |
commit | 302a73c0a72c9f0b55dcdcd6f2b8b1eb78220a98 (patch) | |
tree | 2367a8d59ed6851c6e20acd2070d5775f2862f87 /tests/stdio | |
parent | 0914aca645370e8ff46324d304b8a2acb64567ec (diff) | |
parent | 98a58055fb4f75cc46bd7d3e3eb0b2b65b24bd09 (diff) |
Merge pull request #1370 from inolen/ungetc_fixes
misc ungetc fixes
Diffstat (limited to 'tests/stdio')
-rw-r--r-- | tests/stdio/test_fgetc_ungetc.c | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/tests/stdio/test_fgetc_ungetc.c b/tests/stdio/test_fgetc_ungetc.c new file mode 100644 index 00000000..c69a3d1a --- /dev/null +++ b/tests/stdio/test_fgetc_ungetc.c @@ -0,0 +1,87 @@ +#include <assert.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +static void create_file(const char *path, const char *buffer, int mode) { + int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, mode); + assert(fd >= 0); + + int err = write(fd, buffer, sizeof(char) * strlen(buffer)); + assert(err == (sizeof(char) * strlen(buffer))); + + close(fd); +} + +void setup() { + create_file("file.txt", "cd", 0666); +} + +void cleanup() { + unlink("file.txt"); +} + +void test() { + FILE *file; + int err; + char buffer[256]; + + file = fopen("file.txt", "r"); + assert(file); + + // pushing EOF always returns EOF + rewind(file); + err = ungetc(EOF, file); + assert(err == EOF); + + // ungetc should return itself + err = ungetc('a', file); + assert(err == (int)'a'); + + // push two chars and make sure they're read back in + // the correct order (both by fgetc and fread) + rewind(file); + ungetc('b', file); + ungetc('a', file); + err = fgetc(file); + assert(err == (int)'a'); + fread(buffer, sizeof(char), sizeof(buffer), file); + assert(!strcmp(buffer, "bcd")); + + // rewind and fseek should reset anything that's been + // pushed to the stream + ungetc('a', file); + rewind(file); + err = fgetc(file); + assert(err == (int)'c'); + ungetc('a', file); + fseek(file, 0, SEEK_SET); + err = fgetc(file); + assert(err == (int)'c'); + + // fgetc, when nothing is left, should return EOF + fseek(file, 0, SEEK_END); + err = fgetc(file); + assert(err == EOF); + err = feof(file); + assert(err); + + // ungetc should reset the EOF indicator + ungetc('e', file); + err = feof(file); + assert(!err); + + fclose(file); + + puts("success"); +} + +int main() { + atexit(cleanup); + signal(SIGABRT, cleanup); + setup(); + test(); + return EXIT_SUCCESS; +}
\ No newline at end of file |