c++ - 为什么它拒绝将整数的二进制写入文件?
问题描述
我遇到了这个问题-当我尝试将整数的二进制文件写入文件时,它不会将其写入 Delivery 文件中。
我的整个想法是获取整数,将其转换为二进制,然后将其写入文件。之后,如果需要,我会回到程序中,写入一个新的整数值,然后将新值添加到已经写入的值中。即文件中的“5”,回来,写“3”,然后文件中有8。
这是代码:
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
char answer;
struct PRODUCT {
string product_name;
int quantity;
PRODUCT() : product_name(""), quantity(0) {}
} product;
int main () {
fstream delivery_file("files/Delivery", ios::app | ios::in | ios::out | ios::binary);
do {
if (delivery_file.is_open()) {
cout << "\nPlease input the name of a product: ";
getline(cin, product.product_name);
cout << "\nPlease input the quantity of a product: ";
string str;
getline(cin, str);
product.quantity = atoi(str.c_str());
bool foundAndReplaced = false;
while (!delivery_file.eof())
{
PRODUCT temp_prod;
while (!delivery_file.eof())
{
char ch = delivery_file.get();
temp_prod.product_name += ch;
if (ch == 0)
{
break;
}
}
if (delivery_file.eof() && delivery_file.tellg() == ios::beg)
{
cout << "Error: Unexpected end of file.\n";
delivery_file.clear();
break;
}
if (temp_prod.product_name == product.product_name)
{
delivery_file.seekp(delivery_file.tellg());
delivery_file.read((char*)(temp_prod.quantity), sizeof(PRODUCT::quantity));
product.quantity += temp_prod.quantity;
delivery_file.write((char*)(product.quantity), sizeof(PRODUCT::quantity));
foundAndReplaced = true;
}
}
if (!foundAndReplaced)
{
delivery_file.write(product.product_name.c_str(), product.product_name.length() + 1);
delivery_file.write((char*)(&product.quantity), sizeof(product.quantity));
}
}
else {
cout << "Unable to open file";
}
cout << "Do you want to add more products? Y/N \n";
answer = 0;
while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N')
{
answer = _getch();
}
}
while(answer == 'Y' || answer == 'y');
delivery_file.close();
cout << "\nDeliveries registered.\n";
return 0;
}
解决方案
使用ios::binary
不会导致它将二进制数据写入文件,它只是禁用一些格式,请参阅What the point of using std::ios_base::binary? 例如。
如果您希望将整数作为二进制文件写入文件,我建议您使用以下内容:
int foo = 0x0F00;
ofstream bar("test.txt", ios::out | ios::binary);
bar.write(reinterpret_cast<char*>(&foo), sizeof(int));
bar.close();
这将采用整数,将其重新解释为字符序列并将其输出到文件而不进行格式化(ios::binary
为此需要)。
看到你已经编辑了这个问题:你不能像这样在磁盘上求和,你只能以字节为单位写入,这将覆盖以前存在的任何数据。要做你想做的事,你必须阅读这个数字,总结它,然后再写下来。你可以通过使用foo.read(...)
with foo
now beingfstream
和 opens with来做到这ios::in
一点。