fgetc没有递增指针或递减fpos_t对象(C)

时间:2014-10-08 00:43:41

标签: c pointers fgetc

所以我找不到这个问题的答案。

是否有:

  1. 一个类似于fgetc的函数,可以在不增加指针的情况下检索指针处的字符吗?

  2. 或者减少fpos_t对象而不减少其下方指针的方法。(对这个答案最感兴趣)

  3. 对于C.

1 个答案:

答案 0 :(得分:3)

您有三种选择:

1)使用ftell / fseek

示例:

  FILE * pFile;
  char c1, c2;
  long offset;
  pFile = fopen ( "example.txt" , "r" );
  offset = ftell(pFile);
  c1 = fgetc(pFile);
  fseek ( pFile , offset , SEEK_SET );
  c2 = fgetc(pFile);
  /* result: c1 == c2 */

(注意:对于二进制流,您也可以尝试使用fseek(pFile, -1, SEEK_CUR)但是对于文本模式,如上所述,获取一个字符可能会使指针超过一个位置。)

2)use fgetpos / fsetpos

示例:

  FILE * pFile;
  fpos_t position;
  char c1, c2; 
  pFile = fopen ("example.txt","r");
  fgetpos (pFile, &position);
  c1 = fgetc(pFile);
  fsetpos (pFile, &position);
  c2 = fgetc(pFile);
  /* result: c1 == c2 */

3)使用ungetc

  FILE * pFile;
  char c1, c2;
  c1 = fgetc(pFile);
  ungetc(c1, pFile);
  c2 = fgetc(pFile);
  /* result: c1 == c2 */

这些方法中哪一种更有效,取决于平台和实现。例如。例如,它可能会在引擎盖ungetc下重新读取当前的块直到当前点。或者它可能只是将指针移动到内存缓冲区中。