I am trying to write a char* to a binary file.
This is what I have now.
void Write(char* fileName, char* pData)
{
ofstream binFile (fileName, ios::out | ios::binary);
if (binFile.open())
{
binFile.write((char*)&pData, sizeof(pData));
binFile.close();
}
}
void Read(char* fileName, char* pData)
{
ifstream binFile(fileName, ios::in | ios::binary);
if(binFile.open())
{
binFile.read(char*)&pData, sizeof(pData));
binFile.close
}
}
int main()
{
char* testData = "ABCdEFG"; // not real data
char* getTestData;
char* file = "C:\\testData.dat";
Write(file, testData);
Read(file, getTestData);
}
Test data will be of unknown length. May not always be the same.
When i run the program once, and write and read. I can get back the test data.
But when i stop the program and run it again, this time without writing. Just reading, i cannot get back the test data.
I don't really understand whats happening here. Can some one explain it to me?
is wrong. It just writes the value of the pointer. It does not write the data.
You need to use:
However, that won't be adequate to read the data back. To be able to read the data back, you'll need to write the size of the string first.
And when reading the data back, you will need to use:
and then, null terminate the string.
PS
Make sure
getTestData
is properly initialized before using it to read the data.will be adequate for your test case.
Update
You can make your program a bit better by using
std::string
instead ofchar*
. The size of the saved data can be more easily managed when astd::string
is used.