Search code examples
cstdiofseek

Move the file pointer back after fseek


I know this question sounds silly, but I cannot figure out when I am modifying my file pointer. I just started learning how files work in C. I was doing a simple exercise where I have to write function that shows size of file and takes file pointer as parameter. This is my function:

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

But the system shows that I cannot modify the file pointer. I thought that all I had to do is write fseek(f,0,SEEK_SET); after size... to set cursor back to original place but it didn't work.

This is how system check function:

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

After checking it says "FAIL - function should not modify file pointer "


Solution

  • Your function should set the file back to the position it was in when called:

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

    Best of luck.