fseek后将文件指针移回

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

我知道这个问题听起来很傻,但是当我修改文件指针时,我无法弄明白。我刚刚开始学习文件如何在C中工作。我正在做一个简单的练习,我必须编写显示文件大小的函数并将文件指针作为参数。这是我的功能:

int file_size_from_file(FILE *f)
{
    int size;
    if(f==NULL)
    {
        return -2;
    }
    fseek (f, 0, SEEK_END);
    size = ftell(f);
    return size;
}

但系统显示我无法修改文件指针。我认为我所要做的就是在fseek(f,0,SEEK_SET);之后写size...将光标设置回原来的位置,但它不起作用。

这是系统检查功能:

FILE *f = fopen("bright", "r");

int pos = 7220;

fseek(f, pos, SEEK_SET);

printf("#####START#####");
int res = file_size_from_file(f);
printf("#####END#####\n");

test_error(res == 7220, "Funkcja file_size_from_file zwróciła nieprawidłową wartość, powinna zwrócić %d, a zwróciła %d", 7220, res);
test_error(ftell(f) == pos, "Function should not modify file pointer");

fclose(f);

检查后显示“FAIL - 函数不应该修改文件指针”

c stdio fseek
1个回答
2
投票

您的函数应该将文件设置回调用时的位置:

long int file_size_from_file(FILE *f)
  {
  long int size;
  long int pos;

  if(f==NULL)
    return -2;

  pos = ftell(f);

  fseek (f, 0, SEEK_END);
  size = ftell(f);
  fseek (f, pos, SEEK_SET);

  return size;
  }

祝你好运。

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