I need to write float price on a file using write function not << operator but it crashes
int addDevice(fstream & f, Device & d)
{
char buffer[200];
strcpy(buffer, d.id);
strcat(buffer, "#");
strcat(buffer, d.name);
strcat(buffer, "#");
short length = strlen(buffer) + sizeof(d.price);
char c = '$';
f.seekp(0, ios::end);
f.write((char*) & c, 1);
f.write((char*)&length, sizeof(length));
f.write(buffer, length);
f.write((char *) & d.price, sizeof(float));
f.write((char *)'#', 1);
f.seekp(0, ios::beg);
return length;
}
The problem is likely to be the line
f.write((char *)'#', 1);
This reinterprets the numerical value of '#'
(ie, 35) as a memory address, dereferences that address and would write the byte at that address into f
if that address were valid, which it isn't. This is where you get undefined behaviour and probably a crash (although you can't depend on it that this sort of thing always crashes).
I think you want
f.put('#');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.