特殊文件夹的 fseek 和 ftell 的奇怪返回 [重复]

问题描述 投票:0回答:1

对于具有 rb 模式的目录 fopen 返回非空值。 对于某些带有 SEEK_END 的 fseek 文件夹返回 0,对于其他文件夹返回 -1。 为此,fseek 返回 0 ftell 返回 INT64_MAX。

为什么会这样? 为什么可以使用 rb 模式为目录调用 fopen?

操作系统:

Ubuntu 22.04.1 LTS

clang --版本:

Ubuntu clang version 14.0.6

编译命令:

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;
}

输出:

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
c linux glibc fseek ftell
1个回答
3
投票

没什么奇怪的,数字 9223372036854775807 是 2^63-1.

如果转换为有符号将为 -1,

ftell
刚刚失败,您可以打印
errno
以查看其失败的原因。

© www.soinside.com 2019 - 2024. All rights reserved.