Directories do not exist in the C99 (or C2011) standard. Thus, by definition, fopen -ing a directory is implementation-specific or undefined.
fopen (3) may fail (giving a NULL result). fseek (3) can also fail (returning -1). And then you better check errno (3) or use perror (3)
ftell documented to return long and -1L on failure. On 64-bit Linux, this is 0xffffffffffffffff .
Instead, the code should be
FILE* fd = fopen(argv[1], "rb"); if (!fd) { perror(argv[1]); exit(EXIT_FAILURE); }; if (fseek(fd, 0, SEEK_END)<0) { perror("fseek"); exit(EXIT_FAILURE); }; long flen = ftell(fd); if (flen == -1L) { perror("ftell"); exit(EXIT_FAILURE); };
BTW, on Linux / Debian / Sid / AMD64 with the libc-2.17 and 3.10.6 kernel, the codes work fine when argv[1] is /tmp ; unexpectedly, flen is LONG_MAX ie 0x7fffffffffffffff
By the way, in Linux directories are a special case of files. Use stat (2) in the file path (and fstat to the file descriptor , possibly obtained with fileno (3) from some FILE* ) to find out more metadata about a file, including its "type" (via its mode ) You want opendir (3) , readdir (3), and closedir (3) to work with the contents of the directory. See also inode (7) .
source share