In an array like int a[5] we can store 5 values from a[0] to a[4]. not this..?
I have a char mobile[10] variable in my class and I was storing exactly 10 character long string in this variable. But when I am reading it from file, a few characters from the next variable (declared just after this variable in class) are being appended in variable mobile. It took hours to investigate what is wrong.
I tried everything I could by changing the order of variable etc.
At last I’d set the size of mobile to 11 (char mobile[11]) and then store it into the binary file. Then everything goes well.
Here I have created a demo program that can demonstrate my study:
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <fstream.h>
#include <stdio.h>
class Test
{
public:
char mobile[10], address[30];
};
void main()
{
clrscr();
Test t;
// uncoment below to write to file
/*strcpy(t.mobile, "1234567890");
strcpy(t.address, "Mumbai");
fstream f("_test.bin", ios::binary | ios::out | ios::app);
f.write((char*)&t, sizeof(t));*/
// uncomment below to read from file
/*fstream f("_test.bin", ios::binary | ios::in);
f.read((char*)&t, sizeof(t));
cout << t.mobile << "\t" << t.address;*/
f.close();
getch();
}
Is my assumption correct that I can not store n characters in an array like char[n] when working with files more specifically with binary files..?
Should I always take 1 extra size of required size..??
My compiler is Turbo C++ (may be 3.0). It is very old and discontinued product.
character pointers in C/C++ must be null terminated. That means you must allot another character with value of ‘\0’ at the end.
Also note,
strcpyfunction copies all the characters from one string to another, until\0is encountered, unless its a const string(an example is “hello world”) which is stored as “hello world\0” during compilation.Try this code: