[英]Writing/Reading strings in binary file-C++
我搜索了类似的帖子,但找不到可以帮助我的东西。
我正在尝试先写一个包含字符串的字符串长度的整数,然后将该字符串写到二进制文件中。
但是,当我从二进制文件读取数据时,我读取了value = 0的整数,并且我的字符串中包含垃圾。
例如,当我输入“ asdfgh”作为用户名,输入“ qwerty100”作为密码时,两个字符串长度都得到0,0,然后从文件中读取垃圾。
这就是我将数据写入文件的方式。
std::fstream file;
file.open("filename",std::ios::out | std::ios::binary | std::ios::trunc );
Account x;
x.createAccount();
int usernameLength= x.getusername().size()+1; //+1 for null terminator
int passwordLength=x.getpassword().size()+1;
file.write(reinterpret_cast<const char *>(&usernameLength),sizeof(int));
file.write(x.getusername().c_str(),usernameLength);
file.write(reinterpret_cast<const char *>(&passwordLength),sizeof(int));
file.write(x.getpassword().c_str(),passwordLength);
file.close();
就在下面的相同功能中,我读取了数据
file.open("filename",std::ios::binary | std::ios::in );
char username[51];
char password[51];
char intBuffer[4];
file.read(intBuffer,sizeof(int));
file.read(username,atoi(intBuffer));
std::cout << atoi(intBuffer) << std::endl;
file.read(intBuffer,sizeof(int));
std::cout << atoi(intBuffer) << std::endl;
file.read(password,atoi(intBuffer));
std::cout << username << std::endl;
std::cout << password << std::endl;
file.close();
当读回数据时,您应该执行以下操作:
int result;
file.read(reinterpret_cast<char*>(&result), sizeof(int));
这将直接将字节读取到result
的内存中, result
不会隐式转换为int。 这将首先恢复写入文件的确切二进制模式,并因此恢复您的原始int
值。
file.write(reinterpret_cast<const char *>(&usernameLength),sizeof(int));
这会从&usernameLength;中写入sizeof(int)个字节。 它是整数的二进制表示形式,并且取决于计算机体系结构(小端与大端)。
atoi(intBuffer))
这会将ascii转换为整数,并期望输入包含字符表示形式。 例如,intBuffer = {'1','2'}-将返回12。
您可以尝试以与编写相同的方式阅读它-
*(reinterpret_cast<int *>(&intBuffer))
但这可能会导致未对齐的内存访问问题。 更好地使用JSON之类的序列化格式,这将有助于以跨平台方式读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.