在fseek

时间:2019-04-20 21:36:11

标签: c stdio fseek

我知道这个问题听起来很愚蠢,但是我无法弄清何时修改文件指针。我刚刚开始学习文件在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);

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

1 个答案:

答案 0 :(得分: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;
  }

好运。

相关问题