写入二进制文件
writing into binary files
本文关键字:二进制文件 更新时间:2023-10-16
#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;
}
我不知道如何写超过1个变量到一个文件,请帮助,我包括一个例子;)也许有更好的方法写入文件,请帮助我解决这个问题,这对我来说很难解决
对于文本文件,您可以使用与std::cout
类似的<<
轻松地每行输出一个变量。
对于二进制文件,您需要使用std::ostream::write()
,它写入一个字节序列。对于age
属性,您需要将reinterpret_cast
改为const char*
,并写入尽可能多的字节,以便为您的机器架构保存int
。注意,如果您打算在另一台机器上读取这个二进制日期,则必须考虑字长和端序。我还建议您在使用name
和surname
缓冲区之前将它们归零,以免您最终在二进制文件中出现未初始化内存的工件。
同样,也不需要将类的属性传递给to_file()
方法。
#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 ..
File.write(name, 15);
File.write(surname, 15);
File.write((char *) &age, sizeof(age));
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作