Why does ftell () show the wrong position after fread ()?

I get a very strange error when trying to read from a simple text file with a call to c fread ().
I made a very simple program to show this 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

This is normal? fread returns the number "1000", but the cursor (with ftell ()) shows 1007, and any help would be appreciated.

+5
source share
3 answers

This is normal.

'\n' can be represented by two characters, so there is a distortion that you get.

If you do not want this, open the final in binary mode.

+10
source

From the documentation ftell:

, . , fseek.

, .

+4

Let_Me_Be . , " " (EOL) . , Windows, "r" ( ), , "\ r\n", "\n". , , , Windows '\ r\n', '\n'. Unix- . Mac '\ r' End of Line, , '\n' EOL. , '\n', () (\ r\n).

+1

All Articles