Strange return of fseek & ftell for special folder

32 Views Asked by At

For directories fopen with rb mode return non-null value. For some folders fseek with SEEK_END return 0, for others return -1. For which fseek return 0 ftell return INT64_MAX.

Why is this happening? Why is it possible to call fopen for directories with rb mode?

OS: Ubuntu 22.04.1 LTS

clang --version: Ubuntu clang version 14.0.6

Compile command: clang main.c -o main

#include <stdio.h>
#include <gnu/libc-version.h>

void test_open(const char* filename){
   printf("\nPath = %s\n", filename);
   FILE* file = fopen(filename, "rb");
   if (!file) {
      puts("Not found!\n");
      return;
   }
   size_t size = 0;
   printf("fseek 0 SEEK_END = %d\n", fseek(file, 0, SEEK_END));
   long length = ftell(file);
   printf("ftell = %ld\n", length);
   printf("fseek 0 SEEK_SET = %d\n", fseek(file, 0, SEEK_SET));
   fclose(file);
}

int main(int argc, char **argv) {
   puts(gnu_get_libc_version());
   test_open("/");
   test_open("/home/");
   test_open("/home/user/");
   test_open("/home/user/test_src/");
   test_open("/home/user/test_src/subdir/");
   return 0;
}

Output:

2.37

Path = /
fseek 0 SEEK_END = -1
ftell = 0
fseek 0 SEEK_SET = 0

Path = /home/
fseek 0 SEEK_END = -1
ftell = 0
fseek 0 SEEK_SET = 0

Path = /home/user/
fseek 0 SEEK_END = -1
ftell = 0
fseek 0 SEEK_SET = 0

Path = /home/user/test_src/
fseek 0 SEEK_END = 0
ftell = 9223372036854775807
fseek 0 SEEK_SET = 0

Path = /home/user/test_src/subdir/
fseek 0 SEEK_END = 0
ftell = 9223372036854775807
fseek 0 SEEK_SET = 0
0

There are 0 best solutions below