seek.c 1.7 KB

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