为什么ftell()在fread()之后显示错误的位置? [英] Why does ftell() shows wrong position after fread()?

查看:126
本文介绍了为什么ftell()在fread()之后显示错误的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试通过c 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;
}

我得到的输出是:

cur before=0
cur after reading 1000 bytes =1007

那正常吗? fread返回数字"1000",但光标(带有ftell())显示1007,将不胜感激.

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

推荐答案

这很正常.

'\n'可以用两个字符表示,所以会有歪斜.

'\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.

这篇关于为什么ftell()在fread()之后显示错误的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆