Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ftell() shows wrong position after fread()?

Tags:

c

file

fread

I'm getting a very strange error while trying to read from a simple text file with c fread() call.
I made a very simple program to show that error:

int main(int argc ,char ** argv) {
  FILE* fh = fopen("adult.txt","r");
  if(fh==NULL){
    printf("error opening file\n");
    exit(0);
  }

  int s = 1000;
  printf("cur before=%d\n",ftell(fh));
  char* b = malloc (sizeof(char)*s);
  int k =fread(b,sizeof(char),s,fh);
  printf("cur after reading %d bytes =%d\n",k,ftell(fh));

  return EXIT_SUCCESS;
}

And what I get as output:

cur before=0
cur after reading 1000 bytes =1007

Is that normal? fread return the number '1000' but the cursor (with ftell()) shows 1007 and any help will be appreciated.

like image 989
ezzakrem Avatar asked May 18 '12 10:05

ezzakrem


2 Answers

That's normal.

'\n' can be represented with two characters, so there is the skew you are getting.

If you don't want that to happen, open the finaly in binary mode.

like image 191
Šimon Tóth Avatar answered Oct 06 '22 23:10

Šimon Tóth


From the documentation of ftell:

or binary streams, the value returned corresponds to the number of bytes from the beginning of the file. For text streams, the value is not guaranteed to be the exact number of bytes from the beginning of the file, but the value returned can still be used to restore the position indicator to this position using fseek.

So yes, this is normal.

like image 27
Sergey Kalinichenko Avatar answered Oct 06 '22 22:10

Sergey Kalinichenko