C++ 如何正确地将数据从二进制文件读取到字符数组
如何将数据从二进制文件正确写入新的字符数组。 我知道这个问题在这里被问了好几次,但我仍然不知道如何正确地去做 这就是我到目前为止所拥有的C++ 如何正确地将数据从二进制文件读取到字符数组,c++,C++,如何将数据从二进制文件正确写入新的字符数组。 我知道这个问题在这里被问了好几次,但我仍然不知道如何正确地去做 这就是我到目前为止所拥有的 struct Computer_Details { char computer_type[99]; int release_year; float price; }; Computer_Details pc_details; cout << "Enter Computer T
struct Computer_Details {
char computer_type[99];
int release_year;
float price;
};
Computer_Details pc_details;
cout << "Enter Computer Type: ";
cin.getline(pc_details.computer_type, 255);
cout << "Enter Computer Release Date: ";
cin >> pc_details.release_year;
cout << "Enter Computer Price: ";
cin >> pc_details.price;
cout << "\n\n";
//Create File
ofstream file;
file.open("PC_Database.data", ios::binary | ios::app);
if (!file) cout << "Couldn't open file\n";
else {
file.write((char*)&pc_details, sizeof(Computer_Details));
file.close();
}
ifstream readFile;
readFile.open("PC_Database.data", ios::binary);
if (!readFile) cout << "Couldn't Open File\n";
else {
readFile.seekg(0, ios::end);
int fileSize = readFile.tellg();
int pcCount = fileSize / sizeof(Computer_Details);
readFile.seekg(0, ios::beg);
Computer_Details *pc_details = new Computer_Details[pcCount];
readFile.read((char*)pc_details, pcCount * sizeof(Computer_Details));
char *buff = new char[299];
for (int i = 0; i < pcCount; i++)
{
//write to buff char
}
readFile.close();
}
struct Computer\u详细信息{
字符计算机_类型[99];
国际发行年;
浮动价格;
};
计算机详细信息pc详细信息;
无法提供pc的详细信息。发布年份;
cout>pc_详细信息。价格;
试试看
std::ifstream输入(szFileName,std::ios::binary);
数据=标准::向量(标准::istreambuf_迭代器(输入),
(std::istreambuf_迭代器());
char*charArray=&数据[0];
size_t arraySize=data.size();
data
vector的缓冲区是所需的字符数组。它的构造函数的参数是两个迭代器。第一个是ifstream
中的当前读取位置(本例中为流的开始)。第二个构造函数是默认的,它被视为一个结束迭代器。问题可能是结构的大小,
检查结构的尺寸,并将其与此结构的尺寸进行比较:
struct Computer_Details {
char computer_type[100];
int release_year;
float price;
};
同样的问题是,当您试图读/写包含bool变量的结构时,它介于两种其他类型(如int)之间
试试这个:
readFile.read((char*)pc_details->computer_type, sizeof(Computer_Details::computer_type));
readFile.read((char*)pc_details->release_year, sizeof(Computer_Details::release_year));
readFile.read((char*)pc_details->price, sizeof(Computer_Details::price));
编辑:看看这篇评论中的例子:我猜你想把pc_的细节放到buff中,这样你就可以把它发送到某个地方并重建数据
如果是这种情况,您可以这样做:
for( int i=0; i < pcCount; i++ )
{
memcpy( buff, (char*)pc_details, sizeof(computer_details));
buff += sizeof(computer_details);
pc_details++;
}
for(int i=0;i
但是,在执行此操作时,必须注意对齐并提供
相应地填充。你的代码应该检查你的数组边界。你可以使用。这个答案的可能重复没有帮助主题:cin.getline(pc\u details.computer\u type,255)之间的长度不匹配
和字符计算机类型[99]
允许溢出计算机类型
。
for( int i=0; i < pcCount; i++ )
{
memcpy( buff, (char*)pc_details, sizeof(computer_details));
buff += sizeof(computer_details);
pc_details++;
}