#include #include #include #include int main() { FILE *fp = fopen("test.txt", "a+"); if (fp == NULL) { puts("failed to open test file in append mode"); exit(1); } size_t written = fwrite("1234567890", 10, 1, fp); if (written != 1) { puts("failed to write"); exit(1); } int ret = fseek(fp, -8, SEEK_CUR); if (ret == -1) { puts("failed to seek"); exit(1); } char read_buf[100]; memset(read_buf, 0, sizeof(read_buf)); size_t read = fread(read_buf, 2, 1, fp); if (read != 1) { printf("failed to read %d\n", errno); exit(1); } if (strcmp(read_buf, "34") != 0) { printf("unexpected read value %s\n", read_buf); exit(1); } ret = ungetc('a', fp); if (ret != 'a') { puts("failed to ungetc"); exit(1); } ret = fseek(fp, 3, SEEK_CUR); if (ret == -1) { puts("failed to seek"); exit(1); } read = fread(read_buf, 2, 1, fp); if (read != 1) { printf("failed to read %d\n", errno); exit(1); } if (strcmp(read_buf, "78") != 0) { printf("unexpected read value %s\n", read_buf); exit(1); } written = fwrite("0987654321", 10, 1, fp); if (written != 1) { puts("failed to write"); exit(1); } ret = fseek(fp, -20, SEEK_CUR); if (ret == -1) { puts("failed to seek"); exit(1); } read = fread(read_buf, 20, 1, fp); if (read != 1) { printf("failed to read %d\n", errno); exit(1); } if (strcmp(read_buf, "12345678900987654321") != 0) { printf("unexpected read value %s\n", read_buf); exit(1); } fclose(fp); puts("success"); return 0; }