Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations cowski on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

Small program, very strange bug

Status
Not open for further replies.

steveo2002

Computer
Jun 28, 2002
2
Hi, I have got this incredibly strange bug happening with some code I've written and I fear there could be something fundamentaly wrong with (either me or) my system.

Here's the code (it's short, I promise):

======================================

#include <stdio.h>
#define FILE_NAME &quot;sdtest.dat&quot;

int main()
{
FILE *fp;
long idx = 0;

fp = fopen(FILE_NAME, &quot;r&quot;);

if (fp)
{
fread(&idx, sizeof(long), 1, fp);
printf(&quot;old: %d\n&quot;,idx);
idx++;
fclose(fp);
}

fp = fopen(FILE_NAME, &quot;w&quot;);

{
printf(&quot;new: %d\n&quot;,idx);
fwrite(&idx, sizeof(long), 1, fp);
}

fclose(fp);
return 0;
}

======================================

The first time I run it I get the following output:

old: 0
new: 1

which increments for each subsequent run, eg.

old: 1
new: 2

then

old: 2
new: 3

etc

BUT, once I have run it enough times for it to get to

old: 25
new: 26

the next run produces

old: 0
new: 1 !!!

The program can not read the file contents when it contains 26! It reads in the file contents of x&quot;1A 00 00 00&quot; as x&quot;00 00 00 00&quot; (verified with debugging).

I have tried this same code on a Unix system at work and there were no problems, what on earth could be causing this? Any insight/advice would be very much appreiated, thanks.

Setup
-----
CPU: AMD Athlon 1GHz
OS: Win 98SE
Compiler: VC++ 6.0
 
Replies continue below

Recommended for you

PS. I know there's some unnecessary braces after the second fopen so you don't have to mention that. :)
 
The text character 27 represents an escape character and as such will not read and write properly to a file in text mode. Change the read write status of the file to &quot;rb&quot; and &quot;wb&quot; then it will properly increment up to 255, once you reach there, you will need to read/write multiple bytes. The reason you did not have the problem with UNIX is it uses binary as the standard IO mode while windows uses text as the standard IO mode. It is always helpful to specify mode to make portability easier.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor