fseek not undoing effects of ungetc correctly (C/C++ programs) on Windows Server 2003 R2 and up.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Symptom: When performing an fseek() after performing a few ungetc() calls on a file stream, with no other intervening file calls, the file pointer is set wrongly and messes up the file stream for good. The fseek() HAS to be on a Negative
index from current position, i.e. ask for rewind back a few characters. This is in a C or C++ program.
Using a combination of ftell() and fseek( , ,SEEK_SET); too does not
help.
Note: I used text stream, and used ftell + fseek. It also happened without ftell i.e. : fseek(filePointer, -3 , SEEK_CUR);
Environment: Visual Studio 6 (cannot upgrade due to legacy code base).
Windows Server 2003 R2 with most updates installed.
Issue happened on Windows Server 2008 as well.
Behavior I believe is not working according to standard: " fseek clears the end-of-file indicator and negates the effect of any prior
ungetc calls against stream."
Sample Code:
<pre class="prettyprint int main()
{
//fopen file
int count = 0;
char ch=?;
FILE *fp = fopen("C:\tmp\data.txt","r");

do{
if( count == 9 ) //Push chars using ungetc()
{
ungetc(Q,fp);
ungetc(R,fp); //Anything more than one ungetc() causes severe issue. Even for one, the fp is set wrongly.
ungetc(S,fp);
ungetc(T,fp);
ungetc(U,fp);
ungetc(V,fp);

//Do an Fseek
long int filePosition = ftell(fp);
filePosition-=3;
fseek(fp,filePosition, SEEK_SET); //This line causes problem.
//fseek(fp, -3, SEEK_CUR); //also did not work.
}
//print ch on screen
printf(" %c ", ch);
count++;
ch = getc(fp);
}while( feof(fp)==0 );

fclose(fp);
return 0;
}[/code]
data.txt for above (all in one line).
<pre class="prettyprint abcdefghijklmnopqrstuvwxyz1234567890)(*&^%$#@![/code]
Output for above (on Windows):
<pre class="prettyprint ? a b c d e f g h i[/code]
Expected output (minor difference might be there, as I might have made minor changes to the program when running on another non windows platform):
<pre class="prettyprint ? a b c d e f g h i f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 0 ) ( * & ^ % $ # @ ![/code]
(Please pardon minor errors in the sample code, I had to distill this out of our complex code and did not spend too much time.
Expectation:
I need someone to tell me how to get this working without making major changes to the code base.

I am pretty sure this is a bug on either Windows/Visual Studio. I have the same code working on many other platforms (Unix based). (I was redirected here by someone from TechNet). I am NOT targeting .NET in any way. Please dont dismiss
this question as using an old version of Visual Studio, can someone try it on a newer version and let me know?<br/>


View the full article
 
Back
Top