You have three options:
1) use ftell / fseek
Example:
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 */
(Remark: for a binary stream, you could also try using fseek(pFile, -1, SEEK_CUR)
but for the text mode, as it was noted, getting one character might advance the pointer more than one position).
2) use fgetpos / fsetpos
Example:
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) use ungetc
FILE * pFile;
char c1, c2;
c1 = fgetc(pFile);
ungetc(c1, pFile);
c2 = fgetc(pFile);
/* result: c1 == c2 */
Which one of these methods is going to be more effective, is platform- and implementation-dependent. E.g. it could be that under the hoods ungetc
, for example, will re-read the current chunk up to the current point. Or it could be that it simply moves the pointer in a memory buffer.