hi all, C++ beginner needs help.
I decided today to give C++ FileIo Streams a little go. since I not played with them much before and have not started out very well
anyway I desided to make a little project that can save the contents of a struct to a file. pretty basic in fact.
My problum is reading back the info. the letter and number displays ok but for some reason str is not. anyway I left my code below if that helps.
VB Code:
#include <iostream> #include <fstream> using namespace std; struct test { int number; char letter; char *str; } aTest; int main(int agvc) { ofstream fout; ifstream fin; // fill struct with some random data aTest.number = 245; aTest.letter = 'A'; //What am I doing wrong here I wonder aTest.str = (char*) malloc(100); strcpy(aTest.str,"Hello World this is a long string"); //write the struct to the file fout.open("C:\\test.txt",ios::binary); fout.write((char*)(&aTest),sizeof(aTest)); fout.close(); // Clear struct of it's data I am only new in C++ // So i am not sure this is the correct way to clear stuff out // tho for the example it be ok I think aTest.letter = '\0'; aTest.number = 0; strcpy(aTest.str,"\0"); //Load the struct back in so we can display the data fin.open("c:\\test.txt",ios::binary); fin.read((char*)(&aTest),sizeof(aTest)); fin.close(); // display the data std::cout << "Number: " << aTest.number << "\n"; std::cout << "Letter: " << aTest.letter << "\n"; std::cout << "String: " << aTest.str << "\n"; // :( why is my str not showing }
anyway hope someone can help
Thanks.





Reply With Quote