sector
asked on
Urgent/Strange fstream & binary file
I have a very strange problem with fstream & binary file
( see the program added )
Every time i write the number 26 to the binary file
the program treats it like an EOF & exist.
#include <fstream.h>
fstream g_File3;
void main()
{
int xx, yy, i1;
g_File3.open("c:\\Temp\\DD _UT.dat", ios::out);
xx = 26;
g_File3.write((unsigned char *)&xx, sizeof(int));
g_File3.write((unsigned char *)&xx, sizeof(int));
g_File3.write((unsigned char *)&xx, sizeof(int));
g_File3.close();
g_File3.open("c:\\Temp\\DD _UT.dat", ios::in);
for (i1 = 0; i1 < 3; i1++)
{
yy = 0;
g_File3.read((unsigned char *)&yy, 4);
cout << g_File3.gcount() << endl << flush;
if (g_File3.eof() == 1)
{
break;
}
}
}
( see the program added )
Every time i write the number 26 to the binary file
the program treats it like an EOF & exist.
#include <fstream.h>
fstream g_File3;
void main()
{
int xx, yy, i1;
g_File3.open("c:\\Temp\\DD
xx = 26;
g_File3.write((unsigned char *)&xx, sizeof(int));
g_File3.write((unsigned char *)&xx, sizeof(int));
g_File3.write((unsigned char *)&xx, sizeof(int));
g_File3.close();
g_File3.open("c:\\Temp\\DD
for (i1 = 0; i1 < 3; i1++)
{
yy = 0;
g_File3.read((unsigned char *)&yy, 4);
cout << g_File3.gcount() << endl << flush;
if (g_File3.eof() == 1)
{
break;
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sorry, but I want to say that Mr. nietod's proposal can not overcome the problem. I have compiled the codes by myself and found that the problem is the data conversion. In the original code, the int type is casted to char by explicit type cast. But the result is meaningless to do it in this way. The correct method is to use Data Conversion routine. In this case, _itoa can be used like this:
char * xxc;
_itoa (xx, xxc, 10);
save xxc to the file instead of xx.
ilanmoshe, if you find the later answer is the right solution, pls do not forget to reject the original one so that the person who provide the right one can get the points.
char * xxc;
_itoa (xx, xxc, 10);
save xxc to the file instead of xx.
ilanmoshe, if you find the later answer is the right solution, pls do not forget to reject the original one so that the person who provide the right one can get the points.
By the way, do you have some special reason that you do not use << and >> operators?
>> In the original code, the int type is casted to char by explicit type cast
No, a POINTER to an int is cast to a POINTER to a char. This is standard practice in binary read/write operations. Also _itoa() converts the data to ASCII, but the point is to write it in binary, not ASCII.
No, a POINTER to an int is cast to a POINTER to a char. This is standard practice in binary read/write operations. Also _itoa() converts the data to ASCII, but the point is to write it in binary, not ASCII.
g_File3.open("c:\\Temp\\DD
I hope this helps. Let me know if not.