关于fstream读写strcut的奇怪问题
定义一个struct:
struct head
{
char v1[8];
char v2[6];
} v_head;
fstream stream;
// 写入文件中
stream.open( "test", ios :: out | ios :: binary );
string v1("ABCABCDE");
sprintf(v_head.v1, v1.c_str());
stream.write( ( char * ) &v_head.v1, sizeof( v_head.v1 ) );
string v2("TODOHP");
sprintf(v_head.v2, v2.c_str());
stream.write( ( char * ) &v_head.v2, sizeof( v_head.v2 ) );
// 从文件中读取
stream.open( "test", ios :: in | ios :: binary );
stream.read( ( char * ) &v_head.v1, sizeof( v_head.v1 ) );
stream.read( ( char * ) &v_head.v2, sizeof( v_head.v2 ) );
cout<<v_head.v1<<"\n"<<v_head.v2<<endl;
★ 迷惑之处
输出结果:
ABCABCDETODOHP <- 对应v_head.v1 ??? 这里不应该是:ABCABCDE 吗?
TODOHP <- 对应v_head.v2
打开test文件,内容如下:
ABCABCDETODOHP
请大家帮忙看看,问题出在哪儿?