seek.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. fd = open("lseek.out", O_RDWR|O_CREAT, 0600);
  25. if (fd == -1) {
  26. perror("open(lseek.out) failed");
  27. return 1;
  28. }
  29. unlink("lseek.out");
  30. fp = fdopen(fd, "rw");
  31. if (fp == NULL) {
  32. perror("fopen(lseek.out) failed");
  33. return 1;
  34. }
  35. memset(buf, 0xAB, sizeof(buf));
  36. ret = write(fd, buf, sizeof(buf));
  37. if (ret != sizeof(buf)) {
  38. fprintf(stderr, "write() failed to write %zi bytes (wrote %li): ", sizeof(buf), (long)ret);
  39. perror("");
  40. return 1;
  41. }
  42. assert(fseeko(fp, 1024, SEEK_SET) == 0);
  43. assert(fseeko(fp, (off_t)-16, SEEK_CUR) == 0);
  44. ret = ftell(fp);
  45. if (ret != (1024-16)) {
  46. fprintf(stderr, "ftell() failed, we wanted pos %i but got %li: ", (1024-16), (long)ret);
  47. perror("");
  48. return 1;
  49. }
  50. for (i = 0; i < ARRAY_SIZE(tests); ++i) {
  51. ret = lseek(fd, tests[i].offset, tests[i].whence);
  52. if (ret != tests[i].offset) {
  53. fprintf(stderr, "lseek(%li,%i) failed (wanted %li, got %li): ", (long)tests[i].offset,
  54. tests[i].whence, (long)tests[i].offset, (long)ret);
  55. perror("");
  56. return 1;
  57. }
  58. ret = fseek(fp, tests[i].offset, tests[i].whence);
  59. if (ret != 0) {
  60. fprintf(stderr, "fseek(%li,%i) failed (wanted 0, got %li): ", (long)tests[i].offset,
  61. tests[i].whence, (long)ret);
  62. perror("");
  63. return 1;
  64. }
  65. }
  66. fclose(fp);
  67. close(fd);
  68. printf("Success!\n");
  69. return 0;
  70. }