-
Need help on fstream...
Say I have an array of ojects, one of the members in each object is a class called string that I have made myself, the one member in the string class is a pointer to char (char* str).
Now I want to write all elements in the array to file, and later read them from the file. I save in biary mode, but since the objects in the array contains objects whith pointers to dynamic memory, I cant use the sizeof operator(?) to know each objects size (where each object starts and stops) in memory, any suggestion on how to solve this?
-
#include <string.h>
int size=strlen(array);
Hope it helps...
-
I think that if you named your class string it might be illegal because that is likely a keyword since there is an STL string class. Call it something else.
-
No, it works fine the file is called strang.h/strang.cpp and the class is named String, so that is not the problem. The problem is to find out how many bytes to read/write to/from file, since one member allocates dynamic memory
-
String classes must reallocate themselves and scan input one character at a time validating it. It should reallocate small blocks of memory such as 20 bytes at a time if it's size is breached. See realloc(...);
String is okay because C++ is case sensitive. Beware of using string or CString.
-
This is how Im going to use my classes, and whats the problem is about. Sorry if I was unclear on the subject.
In main() I create an array of Customer objects whith the new operator, each of the Customer objects contain members of type String object, which in turn has members of type char*.
Now i want to write and read the array in main to/from file in binary mode, how do I do this?
strang.h
class String
{
private:
char* str;
int len;
........more, but not relevant code here
}
customer.h
class Customer
{
private:
int custNo;
String custName;
.........more, but not relevant code here
}
main_file
void main()
{
Customer* cArray = new Customer[10];
.........more, but not relevant code here
}
Thanks for your kind reply
-
For C++ steams read a chapter in a textbook. Many people will use fread to read binary data. Open the file in "rb" mode.
FILE *fptr = fopen("filename","rb");
fread(...); //check compiler help
You can also use fgets or fgetc depending on they type of input that you are loading. The best way to load structures is to use fread.
I can't comment on C++ steams. I have not learned them myself.