Originally Posted by
sam-j89
Code:
enum Status {full, busy, empty};
struct block
{
char* WrdsArray[100];
Status state;
int NumberOfWrds;
int NumberOfBlock;
};
in this struct, you are declaring an array of pointers, which the program will have no problem writing to the file, but the data written will probably not be what you are expecting. the pointer array will be written, but not the data it points to.
iinstead, try the following:
Code:
enum Status {full, busy, empty};
struct block
{
char WrdsArray[100][100];
Status state;
int NumberOfWrds;
int NumberOfBlock;
};
that will allocate space for 100 char arrays of size 100, which will be properly written to the file. also, you have a member of type 'Status'. if this is a struct, ensure that it does not contain any pointers. replace pointer members with actual objects. when you write a struct to a file, you only copy the data between the curly braces. the data that members point to is not replicated.
Code:
int main()
{
fstream myfile;
myfile.open("file1.bin",ios::binary|ios::out);
block b;
for(int i = 0; i<100; i++)
{
b.WrdsArray[i] = " NON ";
}
b.NumberOfBlock = 0;
b.NumberOfWrds = 0;
b.state = empty;
myfile.write(reinterpret_cast<char*>(b),512);
myfile.close();
when i wanna have my program compiled , i get the error :
error C2440: 'reinterpret_cast' : cannot convert from 'block' to 'char *'
that's because 'b' is not a pointer. you can't convert a struct directly to a char pointer. you can, however convert a pointer to that stuct (by using the address-of operator) to a char pointer like so:
Code:
myfile.write(reinterpret_cast<char*>(&b),sizeof(block));
you'll note that I also used the sizeof() operator. this way, you don't have to remember how big your struct is, and also, by specifying a size bigger than your struct, you could potentially read past the end of memory allocated to your process, and have undefined behavior, including corrupt data and frequent crashes.
you will also have to replace
Code:
b.WrdsArray[i] = " NON ";
with
Code:
strcpy(b.WrdsArray[i], " NON ");
because you can't use = to assign the contents of a c-style array.
and when i try to write in another format , like:
instead of
Code:
myfile.write(reinterpret_cast<char*>(b),512);
i get the compiler error :
error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'block' (or there is no acceptable conversion)
if you want to use the << or >> operators with your structs, you need to define those operator overloads yourself. like so:
Code:
std::ostream& operator<< (std::ostream& os, const block& b)
{
return os.write(reinterpret_cast<char*>(&b), sizeof(block));
}
hope this was helpful