C++ 写入二进制文件 #包括 #包括 使用名称空间std; 班级信息{ 私人: 字符名[15]; 查氏[15]; 智力年龄; 公众: 无效输入(){ cout
对于文本文件,如果我有一个以上的int变量,例如C++ 写入二进制文件 #包括 #包括 使用名称空间std; 班级信息{ 私人: 字符名[15]; 查氏[15]; 智力年龄; 公众: 无效输入(){ cout,c++,binary,fstream,C++,Binary,Fstream,对于文本文件,如果我有一个以上的int变量,例如char name[15];char姓氏[15];int age,phone;当使用file.write(name,15);file.write(姓氏,15);file.write((char*)和age&phone,sizeof(age&phone))时,您可以使用类似的每行轻松输出一个变量??@user1069874:不,你不能那样连接它们,你必须单独编写:File.write(name,15);File.write(姓氏,15);File.
char name[15];char姓氏[15];int age,phone;
当使用file.write(name,15);file.write(姓氏,15);file.write((char*)和age&phone,sizeof(age&phone))时,您可以使用类似的每行轻松输出一个变量
??@user1069874:不,你不能那样连接它们,你必须单独编写:File.write(name,15);File.write(姓氏,15);File.write((char*)&age,sizeof(age));File.write((char*)&phone,sizeof(phone));
可能更好File.write((char*)this,sizeof(info))
?@user1069874:您可以这样做,但是为什么要将所有变量作为参数传递给函数呢?嗯,我不知道使用File.write((char*)this,sizeof(info));
然后File使用更多空间/:与您的问题无关,但如果调用ob.input()
不止一次,你会在输入代码中发现一个bug。试着在cin>>age
之后添加std::cin.ignore(100,\n');
。谢谢!也许这有点超出范围,但是有什么工具可以检查二进制文件呢?@MinhTran:是的,这是一个新问题。也许可以看看?
#include <iostream>
#include <fstream>
using namespace std;
class info {
private:
char name[15];
char surname[15];
int age;
public:
void input(){
cout<<"Your name:"<<endl;
cin.getline(name,15);
cout<<"Your surname:"<<endl;
cin.getline(surname,15);
cout<<"Your age:"<<endl;
cin>>age;
to_file(name,surname,age);
}
void to_file(char name[15], char surname[15], int age){
fstream File ("example.bin", ios::out | ios::binary | ios::app);
// I doesn't know how to fill all variables(name,surname,age) in 1 variable (memblock)
//example File.write ( memory_block, size );
File.close();
}
};
int main(){
info ob;
ob.input();
return 0;
}
File.write(name, 15);
File.write(surname, 15);
File.write((char *) &age, sizeof(age));
#include <cstring>
#include <fstream>
#include <iostream>
class info
{
private:
char name[15];
char surname[15];
int age;
public:
info()
:name()
,surname()
,age(0)
{
memset(name, 0, sizeof name);
memset(surname, 0, sizeof surname);
}
void input()
{
std::cout << "Your name:" << std::endl;
std::cin.getline(name, 15);
std::cout << "Your surname:" << std::endl;
std::cin.getline(surname, 15);
std::cout << "Your age:" << std::endl;
std::cin >> age;
to_file();
}
void to_file()
{
std::ofstream fs("example.bin", std::ios::out | std::ios::binary | std::ios::app);
fs.write(name, sizeof name);
fs.write(surname, sizeof surname);
fs.write(reinterpret_cast<const char*>(&age), sizeof age);
fs.close();
}
};
int main()
{
info ob;
ob.input();
}
% xxd example.bin
0000000: 7573 6572 0000 0000 0000 0000 0000 0031 user...........1
0000010: 3036 3938 3734 0000 0000 0000 0000 2f00 069874......../.
0000020: 0000 ..