'Random Characters being stored in a file [closed]
I have created an Admins class with three data members (adminID, adminName, adminPhone) and an array of objects for that same class. The data of each object is to be stored in a .txt file.
There is no run-time error and the program works as expected but upon opening the file in notepad, I found that there are random characters in the file.
Here's the class declaration:
class Admins
{
private:
int adminID;
char adminName[100];
char adminPhone[11];
public:
Admins()
{
adminID = 0;
strcpy(adminName, "NULL");
strcpy(adminPhone, "NULL");
}
void addAdminData();
void writeAdminData();
void readAdminData();
};
This is the snippet for writing the data:
void Admins::writeAdminData()
{
if(adminID == 0)
cout<<"Admin Data not initialized";
else
{
ofstream fout;
fout.open("AdminData.txt", ios::app);
fout.write((char*)this, sizeof(*this));
fout.close();
}
}
This is what the file looked like:
Aryan Soni šÐo ÿÿÿÿ šÐo ÿÿÿÿ @@ € ¶@ ØNr 583963728
Solution 1:[1]
You declared adminID as int so it will be written in binary form, likely 0x00000001, assuming admin's ID is 1. Rest are strings, so adminName, adminPhone should be visible as strings (formally), in "natural language" in notepad.
That's how it is going to look in the file (int is assumed to be 32-bit):
00000000 01 00 00 00 61 64 6d 69 6e 35 35 35 31 32 33 34 |....admin5551234|
00000010 35 |5|
00000011
There are more problems with it. Strings are not terminated in the file so trying to read it one only can know size of int (4 bytes) and the rest is going to be string of characters, unable to differentiate between names. These names should either be terminated somehow (with 0x00, or new line or whatever), or fixed length written to file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
