I want to seek back to a known position in a file. Therefore I use ftell to save the position and later I use fseek to get back.
I know about the restrictions, to seek to a specific position. But this doesn't apply to my case. I have a known position and I want to return to it.
Here the test code I wrote, to simplify the problem. It just saves a position in the file. Reads a string, gets back and rereads the string. And I get an assert, because sometimes I get two different results.
#include "stdlib.h"
#include "crtdbg.h"
int main()
{
FILE *fStream = nullptr;
if (_tfopen_s(&fStream,_T("TestFTell.txt"), _T("rt,ccs=UTF-8")))
return 0;
TCHAR szBuffer1[256], szBuffer2[256];
for (;;)
{
auto pos = ftell(fStream);
_ASSERT(pos!=-1);
if (!_fgetts(szBuffer1, _countof(szBuffer1), fStream))
break;
auto retval1 = fseek(fStream,pos,SEEK_SET);
_ASSERT(retval1!=-1);
auto retval2 = _fgetts(szBuffer2, _countof(szBuffer2), fStream);
_ASSERT(retval2!=0);
_ASSERT(_tcscmp(szBuffer1, szBuffer2)==0);
}
return 0;
}
The program is compiled for unicode use. The text file simply contains some lines, with some lines have UTF-8 chars. Here a test file.
I tested it in VS-2010, VS-2013, VS-2015. In all versions I get an ASSERT.
Is this a bug, or do I misunderstand ftell/fseek?
How can I return to a previous read position in the file?
Or did I discover a bug in the CRT?
PS: In VS-2010 I already filed a bug for this case. They wrote that it will be fixed. Seams that this was never fixed.