seek.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <assert.h>
  8. #define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(*arr))
  9. int main(void)
  10. {
  11. struct {
  12. off_t offset;
  13. int whence;
  14. } tests[] = {
  15. { 0x00, SEEK_SET },
  16. { 0x01, SEEK_SET },
  17. { 0xFF, SEEK_SET }
  18. };
  19. char buf[2000];
  20. off_t ret;
  21. int i, fd;
  22. FILE *fp;
  23. fd = open("lseek.out", O_RDWR|O_CREAT, 0600);
  24. if (fd == -1) {
  25. perror("open(lseek.out) failed");
  26. return 1;
  27. }
  28. unlink("lseek.out");
  29. fp = fdopen(fd, "rw");
  30. if (fp == NULL) {
  31. perror("fopen(lseek.out) failed");
  32. return 1;
  33. }
  34. memset(buf, 0xAB, sizeof(buf));
  35. ret = write(fd, buf, sizeof(buf));
  36. if (ret != sizeof(buf)) {
  37. fprintf(stderr, "write() failed to write %i bytes (wrote %i): ", sizeof(buf), ret);
  38. perror("");
  39. return 1;
  40. }
  41. assert(fseeko(fp, 1024, SEEK_SET) == 0);
  42. assert(fseeko(fp, (off_t)-16, SEEK_CUR) == 0);
  43. ret = ftell(fp);
  44. if (ret != (1024-16)) {
  45. fprintf(stderr, "ftell() failed, we wanted pos %i but got %i: ", (1024-16), ret);
  46. perror("");
  47. return 1;
  48. }
  49. for (i = 0; i < ARRAY_SIZE(tests); ++i) {
  50. ret = lseek(fd, tests[i].offset, tests[i].whence);
  51. if (ret != tests[i].offset) {
  52. fprintf(stderr, "lseek(%i,%i) failed (wanted %i, got %i): ", tests[i].offset,
  53. tests[i].whence, tests[i].offset, ret);
  54. perror("");
  55. return 1;
  56. }
  57. ret = fseek(fp, tests[i].offset, tests[i].whence);
  58. if (ret != 0) {
  59. fprintf(stderr, "fseek(%i,%i) failed (wanted 0, got %i): ", tests[i].offset,
  60. tests[i].whence, ret);
  61. perror("");
  62. return 1;
  63. }
  64. }
  65. fclose(fp);
  66. close(fd);
  67. printf("Success!\n");
  68. return 0;
  69. }